View Category
Define a class
Declare a class named Greeter that takes a string on creation and greets using this string if you call the
"greet" method.
python
class Greeter(object):
""" Greet someone.
"""
def __init__(self, whom):
self._whom = whom
def greet(self):
print "Hello, %s!" % self._whom
Greeter("world").greet()
""" Greet someone.
"""
def __init__(self, whom):
self._whom = whom
def greet(self):
print "Hello, %s!" % self._whom
Greeter("world").greet()
clojure
(defprotocol IGreeter
(greet [this]))
(deftype Greeter [whom]
IGreeter
(greet [this]
(println (str "Hello, " whom))))
(greet (Greeter. "world"))
(greet [this]))
(deftype Greeter [whom]
IGreeter
(greet [this]
(println (str "Hello, " whom))))
(greet (Greeter. "world"))
(defn greeter [whom]
{:whom whom})
(defn greet [g]
(println (str "Hello, " (:whom g))))
(greet (greeter "world"))
{:whom whom})
(defn greet [g]
(println (str "Hello, " (:whom g))))
(greet (greeter "world"))
fsharp
type Greeter(whom' : string) =
member this.greet() = printfn "Hello, %s!" whom'
(new Greeter("world")).greet()
member this.greet() = printfn "Hello, %s!" whom'
(new Greeter("world")).greet()
type Greeter(whom' : string) =
let whom : string = whom'
member this.greet() = printfn "Hello, %s!" whom
(new Greeter("world")).greet()
let whom : string = whom'
member this.greet() = printfn "Hello, %s!" whom
(new Greeter("world")).greet()
type Greeter =
class
val whom : string
new(whom') = { whom = whom' }
member this.greet() = printfn "Hello, %s!" this.whom
end
(new Greeter("world")).greet()
class
val whom : string
new(whom') = { whom = whom' }
member this.greet() = printfn "Hello, %s!" this.whom
end
(new Greeter("world")).greet()
fantom
class Greeter
{
private Str whom
new make(Str whom) { this.whom = whom }
Void greet() { echo("Hello, $whom") }
}
Greeter("world").greet
{
private Str whom
new make(Str whom) { this.whom = whom }
Void greet() { echo("Hello, $whom") }
}
Greeter("world").greet
java
class Greeter
{
public Greeter(String whom) { this.whom = whom; }
public void greet() { System.out.printf("Hello, %s\n", whom); }
private String whom;
}
public class Solution381 {
public static void main(String[] args) {
(new Greeter("world")).greet();
}
}
{
public Greeter(String whom) { this.whom = whom; }
public void greet() { System.out.printf("Hello, %s\n", whom); }
private String whom;
}
public class Solution381 {
public static void main(String[] args) {
(new Greeter("world")).greet();
}
}
cpp
class Greeter
{
public:
Greeter(const std::string& whom);
void greet() const;
private:
std::string whom;
};
int main()
{
Greeter* gp = new Greeter("world");
gp->greet();
delete gp;
}
Greeter::Greeter(const std::string& whom) : whom(whom) {}
void Greeter::greet() const
{
std::cout << "Hello, " << whom << std::endl;
}
{
public:
Greeter(const std::string& whom);
void greet() const;
private:
std::string whom;
};
int main()
{
Greeter* gp = new Greeter("world");
gp->greet();
delete gp;
}
Greeter::Greeter(const std::string& whom) : whom(whom) {}
void Greeter::greet() const
{
std::cout << "Hello, " << whom << std::endl;
}
public ref class Greeter
{
public:
Greeter(String^ whom);
void greet();
private:
initonly String^ whom;
};
int main()
{
(gcnew Greeter(L"world"))->greet();
}
Greeter::Greeter(String^ whom) : whom(whom) {}
void Greeter::greet()
{
Console::WriteLine(L"Hello, {0}", whom);
}
{
public:
Greeter(String^ whom);
void greet();
private:
initonly String^ whom;
};
int main()
{
(gcnew Greeter(L"world"))->greet();
}
Greeter::Greeter(String^ whom) : whom(whom) {}
void Greeter::greet()
{
Console::WriteLine(L"Hello, {0}", whom);
}
Instantiate object with mutable state
Reimplement the Greeter class so that the
For example, if the greetee is changed to
Hello, Tommy!
The getter would then be used to display the line:
I have just greeted Tommy.
'whom' property or data member remains private but is mutable, and is provided with getter and setter methods. Invoke the setter to change the greetee, invoke 'greet', then use the getter in displaying the line, "I have just greeted {whom}.".
For example, if the greetee is changed to
'Tommy' using the setter, the 'greet' method would display:
Hello, Tommy!
The getter would then be used to display the line:
I have just greeted Tommy.
python
class Greeter(object):
_whom = None
def __init__(self, whom):
self._whom = whom
@property
def whom(self):
return self._whom
@propset(whom)
def whom(self, value=None):
self._whom = value
def greet(self):
print 'Helo, %s!' % self._whom
greeter = Greeter('Winston')
greeter.greet()
greeter.whom = 'Tommy'
greeter.greet()
class Greeter(object):
_whom = None
def __init__(self, whom):
self._whom = whom
@property
def whom(self):
return self._whom
@propset(whom)
def whom(self, value=None):
self._whom = value
def greet(self):
print 'Helo, %s!' % self._whom
greeter = Greeter('Winston')
greeter.greet()
greeter.whom = 'Tommy'
greeter.greet()
# required for Python 2.5 or less
def propset(prop):
assert isinstance(prop, property)
def helper(func):
return property(prop.fget, func, prop.fdel, prop.__doc__)
return helper
class Greeter(object):
_whom = None
def __init__(self, whom):
self._whom = whom
@property
def whom(self):
return self._whom
@propset(whom)
def whom(self, value=None):
self._whom = value
def greet(self):
print 'Helo, %s!' % self._whom
greeter = Greeter('Winston')
greeter.greet()
greeter.whom = 'Tommy'
greeter.greet()
def propset(prop):
assert isinstance(prop, property)
def helper(func):
return property(prop.fget, func, prop.fdel, prop.__doc__)
return helper
class Greeter(object):
_whom = None
def __init__(self, whom):
self._whom = whom
@property
def whom(self):
return self._whom
@propset(whom)
def whom(self, value=None):
self._whom = value
def greet(self):
print 'Helo, %s!' % self._whom
greeter = Greeter('Winston')
greeter.greet()
greeter.whom = 'Tommy'
greeter.greet()
clojure
(defn greeter [whom]
(atom {:whom whom}))
(defn get-whom [g]
(:whom @g))
(defn set-whom [g whom]
(swap! g #(conj % {:whom whom})))
(defn greet [g]
(println (str "Hello, " (:whom @g) "!")))
; using the "class"
(let [g (greeter "world")]
(greet g)
(set-whom g "Tommy")
(greet g)
(println (str "I have just greeted " (get-whom g) ".")))
; or same effect without using any variables
(println (str "I have just greeted "
(get-whom (doto (greeter "world")
(greet)
(set-whom "Tommy")
(greet)))
"."))
(atom {:whom whom}))
(defn get-whom [g]
(:whom @g))
(defn set-whom [g whom]
(swap! g #(conj % {:whom whom})))
(defn greet [g]
(println (str "Hello, " (:whom @g) "!")))
; using the "class"
(let [g (greeter "world")]
(greet g)
(set-whom g "Tommy")
(greet g)
(println (str "I have just greeted " (get-whom g) ".")))
; or same effect without using any variables
(println (str "I have just greeted "
(get-whom (doto (greeter "world")
(greet)
(set-whom "Tommy")
(greet)))
"."))
fsharp
type Greeter(name:string) =
let mutable whom = name
member this.Whom
with get () = whom
and set v = whom <- v
member this.Greet() =
printfn "Hello, %s!" whom
let greeter = Greeter("World")
greeter.Greet()
greeter.Whom <- "Tommy"
greeter.Greet()
printfn "I have just greeted %s." greeter.Whom
let mutable whom = name
member this.Whom
with get () = whom
and set v = whom <- v
member this.Greet() =
printfn "Hello, %s!" whom
let greeter = Greeter("World")
greeter.Greet()
greeter.Whom <- "Tommy"
greeter.Greet()
printfn "I have just greeted %s." greeter.Whom
fantom
class Greeter
{
new make(Str whom) { this.whom = whom }
Void greet() { echo("Hello, $whom!") }
Str whom
}
greeter := Greeter("world")
greeter.greet
greeter.whom = "Tommy"
echo("I have just greeted ${greeter.whom}.")
{
new make(Str whom) { this.whom = whom }
Void greet() { echo("Hello, $whom!") }
Str whom
}
greeter := Greeter("world")
greeter.greet
greeter.whom = "Tommy"
echo("I have just greeted ${greeter.whom}.")
java
class Greeter {
private String whom;
public Greeter(String whom) {
this.whom = whom;
}
public String getWhom() {
return whom;
}
public void setWhom(String whom) {
this.whom = whom;
}
public void greet() {
System.out.println("Hello " + whom + "!");
}
}
Greeter greeter = new Greeter("World");
greeter.greet();
greeter.setWhom("Tommy");
greeter.greet();
System.out.println("I have just greeted " + greeter.getWhom() + ".");
private String whom;
public Greeter(String whom) {
this.whom = whom;
}
public String getWhom() {
return whom;
}
public void setWhom(String whom) {
this.whom = whom;
}
public void greet() {
System.out.println("Hello " + whom + "!");
}
}
Greeter greeter = new Greeter("World");
greeter.greet();
greeter.setWhom("Tommy");
greeter.greet();
System.out.println("I have just greeted " + greeter.getWhom() + ".");
cpp
#include <iostream>
using namespace std;
class Greeter {
string whom_;
public:
Greeter(const string &whom) : whom_(whom) {}
string get_whom() const {
return whom_;
}
void set_whom(const string &whom) {
whom_ = whom;
}
void greet() const {
cout << "Hello " << whom_ << "!" << endl;
}
};
int main()
{
Greeter greeter("world");
greeter.greet();
greeter.set_whom("Tommy");
greeter.greet();
cout << "I have just greeted " + greeter.get_whom() << "." << endl;
}
using namespace std;
class Greeter {
string whom_;
public:
Greeter(const string &whom) : whom_(whom) {}
string get_whom() const {
return whom_;
}
void set_whom(const string &whom) {
whom_ = whom;
}
void greet() const {
cout << "Hello " << whom_ << "!" << endl;
}
};
int main()
{
Greeter greeter("world");
greeter.greet();
greeter.set_whom("Tommy");
greeter.greet();
cout << "I have just greeted " + greeter.get_whom() << "." << endl;
}
Implement Inheritance Heirarchy
Implement a Shape abstract class which will form the base of an inheritance hierarchy that models 2D geometric shapes. It will have:
* A non-mutable
* A
* A
* A non-mutable
'name' property or data member set by derived or descendant classes at construction time
* A
'area' method intended to be overridden by derived or descendant classes ( double precision floating point return value)
* A
'print' method (also for overriding) will display the shape's name, area, and all shape-specific values
Two derived or descendant classes will be created:
* Circle -> Constructor requires a 'radius' argument, and a 'circumference' method to be implemented
* Rectangle -> Constructor requires 'length' and 'breadth' arguments, and a 'perimeter' method to be implemented
Instantiate an object of each class, and invoke each objects 'print' method to show relevant details.
python
#Start with the import statements.
import math # necessary to get the value of pi
class Shape(object):
"""Shape Class"""
def __init__(self):
"""Constructor method"""
pass #Do nothing here
def area(self):
"""The area method"""
pass #Do nothing here
def print_(self):
"""
The print method. Note the trailing underscore - this is because
there is a reserved statement called 'print' in python 2.x. The
trailing underscore is the accepted method of re-using names without
rebinding them
"""
print 'The name is: %s' % self.name #Print the only property we currently have
def _getName(self):
"""The getter method for the 'name' property.
Note that getter methods are generally discouraged in python"""
return self._name
_name = None # The leading underscore gives a weak non-public value
# to a variable. Two leading underscores will mangle its
# name at runtime, to make it more difficult to access.
# Note there is no real 'private' variable type in python.
name = property(_getName, doc='The name of this object')
# property statements work like: property(fget=None, fset=None, fdel=None, doc=None)
class Circle(Shape):
"""Circle Class - a sub class of shape"""
def __init__(self, radius, name='Circle'):
"""Constructor method again"""
Shape.__init__(self) # init the super class
self.radius = radius # Store the radius
self._setCircumference()# Function call
self._name = name
def _setCircumference(self):
self.circumference = 2*math.pi*self.radius
def area(self):
'''Return the area of this circle'''
tmpAera = math.pi * self.radius**2
return tmpAera
def print_(self):
'''The print method'''
super(Circle, self).print_() # This calls the print_ method in
# the super classes of Circle, in
# this case Shape
print 'The radius is: %f' % self.radius
print 'The circumference is %f' % self.circumference
print 'The area is: %f' % self.area()
class Rectangle(Shape):
"""The Rectangle Class"""
def __init__(self, length, breadth, name='Rectangle'):
Shape.__init__(self)
self._name = name
self.length = length
self.breadth = breadth
self.perimeter()
def area(self):
return self.breadth*self.length
def perimeter(self):
self._perimeter = self.breadth*2+self.length*2
return self._perimeter # You have a method return a value and still
# safely call it without handling the return
# value. This would be collected by garbage
# collection.
def print_(self):
super(Rectangle, self).print_()
print 'The length is %f and the breadth is %f' %(self.length, self.breadth)
print 'The perimeter is: %f' %self._perimeter
print 'The area is: %f' % self.area()
if __name__ == '__main__':
rectangle = Rectangle(5,3)
circle = Circle(5, name='Round and Round')
rectangle.print_()
circle.print_()
import math # necessary to get the value of pi
class Shape(object):
"""Shape Class"""
def __init__(self):
"""Constructor method"""
pass #Do nothing here
def area(self):
"""The area method"""
pass #Do nothing here
def print_(self):
"""
The print method. Note the trailing underscore - this is because
there is a reserved statement called 'print' in python 2.x. The
trailing underscore is the accepted method of re-using names without
rebinding them
"""
print 'The name is: %s' % self.name #Print the only property we currently have
def _getName(self):
"""The getter method for the 'name' property.
Note that getter methods are generally discouraged in python"""
return self._name
_name = None # The leading underscore gives a weak non-public value
# to a variable. Two leading underscores will mangle its
# name at runtime, to make it more difficult to access.
# Note there is no real 'private' variable type in python.
name = property(_getName, doc='The name of this object')
# property statements work like: property(fget=None, fset=None, fdel=None, doc=None)
class Circle(Shape):
"""Circle Class - a sub class of shape"""
def __init__(self, radius, name='Circle'):
"""Constructor method again"""
Shape.__init__(self) # init the super class
self.radius = radius # Store the radius
self._setCircumference()# Function call
self._name = name
def _setCircumference(self):
self.circumference = 2*math.pi*self.radius
def area(self):
'''Return the area of this circle'''
tmpAera = math.pi * self.radius**2
return tmpAera
def print_(self):
'''The print method'''
super(Circle, self).print_() # This calls the print_ method in
# the super classes of Circle, in
# this case Shape
print 'The radius is: %f' % self.radius
print 'The circumference is %f' % self.circumference
print 'The area is: %f' % self.area()
class Rectangle(Shape):
"""The Rectangle Class"""
def __init__(self, length, breadth, name='Rectangle'):
Shape.__init__(self)
self._name = name
self.length = length
self.breadth = breadth
self.perimeter()
def area(self):
return self.breadth*self.length
def perimeter(self):
self._perimeter = self.breadth*2+self.length*2
return self._perimeter # You have a method return a value and still
# safely call it without handling the return
# value. This would be collected by garbage
# collection.
def print_(self):
super(Rectangle, self).print_()
print 'The length is %f and the breadth is %f' %(self.length, self.breadth)
print 'The perimeter is: %f' %self._perimeter
print 'The area is: %f' % self.area()
if __name__ == '__main__':
rectangle = Rectangle(5,3)
circle = Circle(5, name='Round and Round')
rectangle.print_()
circle.print_()
clojure
(defmulti area :Shape)
(defmulti print :Shape)
; Circle methods
(defn circle [r]
{:Shape :Circle
:name "Circle"
:radius r})
(defn circumference [c]
(* 2 Math/PI (:radius c)))
(defmethod area :Circle [c]
(* Math/PI (:radius c) (:radius c)))
(defmethod print :Circle [c]
(println (format "I am a %s with ->" (:name c)))
(println (format "Radius: %.2f" (:radius c)))
(println (format "Area: %.2f" (area c)))
(println (format "Circumference: %.2f" (circumference c))))
; Rectangle methods
(defn rectangle [l b]
{:Shape :Rectangle
:name "Rectangle"
:length l
:breadth b})
(defn perimeter [r]
(+ (* 2 (:length r)) (* 2 (:breadth r))))
(defmethod area :Rectangle [r]
(* (:length r) (:breadth r)))
(defmethod print :Rectangle [r]
(println (format "I am a %s with ->" (:name r)))
(println (format "Length, Width: %.2f, %.2f" (:length r) (:breadth r)))
(println (format "Area: %.2f" (area r)))
(println (format "Perimeter: %.2f" (perimeter r))))
; usage of the "classes"
(let [shapes (list (circle 4.2) (rectangle 2.7 3.1) (rectangle 6.2 2.6) (circle 17.3))]
(doseq [shape shapes]
(print shape)))
(defmulti print :Shape)
; Circle methods
(defn circle [r]
{:Shape :Circle
:name "Circle"
:radius r})
(defn circumference [c]
(* 2 Math/PI (:radius c)))
(defmethod area :Circle [c]
(* Math/PI (:radius c) (:radius c)))
(defmethod print :Circle [c]
(println (format "I am a %s with ->" (:name c)))
(println (format "Radius: %.2f" (:radius c)))
(println (format "Area: %.2f" (area c)))
(println (format "Circumference: %.2f" (circumference c))))
; Rectangle methods
(defn rectangle [l b]
{:Shape :Rectangle
:name "Rectangle"
:length l
:breadth b})
(defn perimeter [r]
(+ (* 2 (:length r)) (* 2 (:breadth r))))
(defmethod area :Rectangle [r]
(* (:length r) (:breadth r)))
(defmethod print :Rectangle [r]
(println (format "I am a %s with ->" (:name r)))
(println (format "Length, Width: %.2f, %.2f" (:length r) (:breadth r)))
(println (format "Area: %.2f" (area r)))
(println (format "Perimeter: %.2f" (perimeter r))))
; usage of the "classes"
(let [shapes (list (circle 4.2) (rectangle 2.7 3.1) (rectangle 6.2 2.6) (circle 17.3))]
(doseq [shape shapes]
(print shape)))
fsharp
[<AbstractClass>]
type Shape(name:string) =
member this.Name = name
abstract Area : float
abstract Print : unit -> unit
type Circle(name, radius:float) =
inherit Shape(name)
member this.Radius = radius
member this.Circumference =
System.Math.PI * radius * 2.
override this.Area =
System.Math.PI * radius * radius
override this.Print() =
printfn "Circle: %s" this.Name
printfn "Area: %f" this.Area
printfn "Circumference: %f" this.Circumference
printfn "Radius: %f" this.Radius
type Rectangle(name, length:float, breadth:float) =
inherit Shape(name)
member this.Length = length
member this.Breadth = breadth
member this.Perimiter =
(length * 2.) + (breadth * 2.)
override this.Area =
length * breadth
override this.Print() =
printfn "Rectangle: %s" this.Name
printfn "Area: %f" this.Area
printfn "Perimiter: %f" this.Perimiter
printfn "Length: %f" this.Length
printfn "Breadth: %f" this.Breadth
let c = Circle("Foo", 2.1)
let r = Rectangle("Bar", 2.2, 3.3)
c.Print()
printfn ""
r.Print()
type Shape(name:string) =
member this.Name = name
abstract Area : float
abstract Print : unit -> unit
type Circle(name, radius:float) =
inherit Shape(name)
member this.Radius = radius
member this.Circumference =
System.Math.PI * radius * 2.
override this.Area =
System.Math.PI * radius * radius
override this.Print() =
printfn "Circle: %s" this.Name
printfn "Area: %f" this.Area
printfn "Circumference: %f" this.Circumference
printfn "Radius: %f" this.Radius
type Rectangle(name, length:float, breadth:float) =
inherit Shape(name)
member this.Length = length
member this.Breadth = breadth
member this.Perimiter =
(length * 2.) + (breadth * 2.)
override this.Area =
length * breadth
override this.Print() =
printfn "Rectangle: %s" this.Name
printfn "Area: %f" this.Area
printfn "Perimiter: %f" this.Perimiter
printfn "Length: %f" this.Length
printfn "Breadth: %f" this.Breadth
let c = Circle("Foo", 2.1)
let r = Rectangle("Bar", 2.2, 3.3)
c.Print()
printfn ""
r.Print()
fantom
abstract class Shape
{
const Str name
new make(Str name) { this.name = name }
abstract Float area()
abstract Void print()
}
class Circle : Shape
{
private Float radius
new make(Float radius) : super("circle") { this.radius = radius }
Float circumference() { return 2 * Float.pi * radius }
override Float area() { return Float.pi * radius.pow(2.0f) }
override Void print()
{
echo("I am a $name with radius $radius, area $area
and circumference $circumference")
}
}
class Rectangle : Shape
{
private Float length
private Float breadth
new make(Float length, Float breadth) : super("rectangle")
{
this.length = length
this.breadth = breadth
}
Float perimeter() { return 2 * (length + breadth) }
override Float area() { return length * breadth }
override Void print()
{
echo("I am a $name with length $length, breadth $breadth,
area $area and perimeter $perimeter")
}
}
circle := Circle(4.0f)
circle.print
rectangle := Rectangle(2.0f, 5.5f)
rectangle.print
{
const Str name
new make(Str name) { this.name = name }
abstract Float area()
abstract Void print()
}
class Circle : Shape
{
private Float radius
new make(Float radius) : super("circle") { this.radius = radius }
Float circumference() { return 2 * Float.pi * radius }
override Float area() { return Float.pi * radius.pow(2.0f) }
override Void print()
{
echo("I am a $name with radius $radius, area $area
and circumference $circumference")
}
}
class Rectangle : Shape
{
private Float length
private Float breadth
new make(Float length, Float breadth) : super("rectangle")
{
this.length = length
this.breadth = breadth
}
Float perimeter() { return 2 * (length + breadth) }
override Float area() { return length * breadth }
override Void print()
{
echo("I am a $name with length $length, breadth $breadth,
area $area and perimeter $perimeter")
}
}
circle := Circle(4.0f)
circle.print
rectangle := Rectangle(2.0f, 5.5f)
rectangle.print
java
/*
* Will work with version 1.4 if you remove the @Override annotation
* and declare floating point numbers using the primitive "double"
*/
abstract class Shape {
protected final String name;
public Shape(String name) {
this.name = name;
}
public abstract Double area();
public abstract void print();
}
class Circle extends Shape {
private Double radius;
public Circle(Double radius) {
super("circle");
this.radius = radius;
}
@Override
public Double area() {
return Math.PI * Math.pow(radius, 2);
}
@Override
public void print() {
System.out.println("A " + name + " with radius " + radius
+ ", area " + area() + " and circumference "
+ circumference() + ".");
}
public Double circumference() {
return 2 * Math.PI * radius;
}
}
class Rectangle extends Shape {
private Double length, breadth;
public Rectangle(Double length, Double breadth) {
super("Rectangle");
this.length = length;
this.breadth = breadth;
}
@Override
public Double area() {
return length * breadth;
}
public Double perimeter() {
return 2 * length + 2 * breadth;
}
@Override
public void print() {
System.out.println("A " + name + " with length " + length
+ ", breadth " + breadth + ", area " + area()
+ " and perimeter " + perimeter() + ".");
}
}
Circle circle = new Circle(4d);
circle.print();
Rectangle rectangle = new Rectangle(2d, 5.5);
rectangle.print();
* Will work with version 1.4 if you remove the @Override annotation
* and declare floating point numbers using the primitive "double"
*/
abstract class Shape {
protected final String name;
public Shape(String name) {
this.name = name;
}
public abstract Double area();
public abstract void print();
}
class Circle extends Shape {
private Double radius;
public Circle(Double radius) {
super("circle");
this.radius = radius;
}
@Override
public Double area() {
return Math.PI * Math.pow(radius, 2);
}
@Override
public void print() {
System.out.println("A " + name + " with radius " + radius
+ ", area " + area() + " and circumference "
+ circumference() + ".");
}
public Double circumference() {
return 2 * Math.PI * radius;
}
}
class Rectangle extends Shape {
private Double length, breadth;
public Rectangle(Double length, Double breadth) {
super("Rectangle");
this.length = length;
this.breadth = breadth;
}
@Override
public Double area() {
return length * breadth;
}
public Double perimeter() {
return 2 * length + 2 * breadth;
}
@Override
public void print() {
System.out.println("A " + name + " with length " + length
+ ", breadth " + breadth + ", area " + area()
+ " and perimeter " + perimeter() + ".");
}
}
Circle circle = new Circle(4d);
circle.print();
Rectangle rectangle = new Rectangle(2d, 5.5);
rectangle.print();
cpp
#include <string>
#include <iostream>
using namespace std;
static const double PI = 3.141592;
class Shape {
protected:
string name_;
public:
Shape(const string& name) : name_(name) { }
virtual double area() const = 0;
virtual void print() const = 0;
};
class Circle : public Shape {
double radius_;
public:
Circle(double radius) : Shape("circle"), radius_(radius) { }
double area() const {
return PI * radius_ * radius_;
}
void print() const {
cout << "A " << name_ << " with radius " << radius_ << ", area "
<< area() << " and circumference " << circumference() << "."
<< endl;
}
double circumference() const {
return 2 * PI * radius_;
}
};
class Rectangle : public Shape {
double length_;
double breadth_;
public:
Rectangle(double length, double breadth) :
Shape("rectangle"), length_(length), breadth_(breadth) { }
double area() const {
return length_ * breadth_;
}
void print() const {
cout << "A " << name_ << " with length " << length_ << ", breadth "
<< breadth_ << ", area " << area() << " and perimeter "
<< perimeter() << "." << endl;
}
double perimeter() const {
return 2 * length_ + 2 * breadth_;
}
};
int main(int argc, char *argv[])
{
Circle circle(4);
circle.print();
Rectangle rectangle(2, 5.5);
rectangle.print();
}
#include <iostream>
using namespace std;
static const double PI = 3.141592;
class Shape {
protected:
string name_;
public:
Shape(const string& name) : name_(name) { }
virtual double area() const = 0;
virtual void print() const = 0;
};
class Circle : public Shape {
double radius_;
public:
Circle(double radius) : Shape("circle"), radius_(radius) { }
double area() const {
return PI * radius_ * radius_;
}
void print() const {
cout << "A " << name_ << " with radius " << radius_ << ", area "
<< area() << " and circumference " << circumference() << "."
<< endl;
}
double circumference() const {
return 2 * PI * radius_;
}
};
class Rectangle : public Shape {
double length_;
double breadth_;
public:
Rectangle(double length, double breadth) :
Shape("rectangle"), length_(length), breadth_(breadth) { }
double area() const {
return length_ * breadth_;
}
void print() const {
cout << "A " << name_ << " with length " << length_ << ", breadth "
<< breadth_ << ", area " << area() << " and perimeter "
<< perimeter() << "." << endl;
}
double perimeter() const {
return 2 * length_ + 2 * breadth_;
}
};
int main(int argc, char *argv[])
{
Circle circle(4);
circle.print();
Rectangle rectangle(2, 5.5);
rectangle.print();
}
Implement and use an Interface
Create a Serializable interface consisting of
* Accept a stream or handle or descriptor argument for the source or destination
* Save to destination or restore from source the properties or data members of the implementing class (restrict yourself to the primitive types
Next, create a Person class which has
'save' and 'restore' methods, each of which:
* Accept a stream or handle or descriptor argument for the source or destination
* Save to destination or restore from source the properties or data members of the implementing class (restrict yourself to the primitive types
'int' and 'string')
Next, create a Person class which has
'name' and 'age' properties or data members and implements this interface. Instantiate a Person object, save it to a serial stream, and instantiate a new Person object by restoring it from the serial stream.
python
import pickle
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return "Name: {name}, age: {age}".format(name=self.name, age=self.age)
person = Person("Gaylord Focker", 21)
with open("person.pickle", "wb") as outstream:
pickle.dump(person, outstream)
with open("person.pickle", "rb") as instream:
deserialized_person = pickle.load(instream)
print(deserialized_person)
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return "Name: {name}, age: {age}".format(name=self.name, age=self.age)
person = Person("Gaylord Focker", 21)
with open("person.pickle", "wb") as outstream:
pickle.dump(person, outstream)
with open("person.pickle", "rb") as instream:
deserialized_person = pickle.load(instream)
print(deserialized_person)
clojure
(defn person [name age]
{:name name :age age})
(defn show [p]
(println (format "Name=%s Age=%d" (:name p) (:age p))))
(defn save [p filename]
(with-out-writer filename (pr p)))
(defn restore [filename]
(read (PushbackReader. (reader filename))))
(let [p (person "Ken" 38)]
(show p)
(save p *person-fn*))
(let [ser-p (restore *person-fn*)]
(show ser-p))
{:name name :age age})
(defn show [p]
(println (format "Name=%s Age=%d" (:name p) (:age p))))
(defn save [p filename]
(with-out-writer filename (pr p)))
(defn restore [filename]
(read (PushbackReader. (reader filename))))
(let [p (person "Ken" 38)]
(show p)
(save p *person-fn*))
(let [ser-p (restore *person-fn*)]
(show ser-p))
fsharp
// Since everyone else is using built-in functionality instead of
// defining an interface as required, I won't buck the trend.
// Maybe this problem should be named "Use serialization features" instead
// of "Implement and use an Interface"
open System
open System.IO
open System.Runtime.Serialization.Formatters.Binary
[<Serializable>]
type Person(name:string, age:int) =
member this.Name = name
member this.Age = age
let serialize x =
use ms = new MemoryStream()
let bf = new BinaryFormatter()
bf.Serialize(ms, x)
ms.ToArray()
let deserialize<'a> bytes =
use ms = new MemoryStream(bytes:byte[])
let bf = new BinaryFormatter()
bf.Deserialize(ms) :?> 'a
let before = Person("Joel", 35)
let bytes = serialize before
let after = deserialize<Person> bytes
printfn "Before: %s, %i" before.Name before.Age
printfn "After: %s, %i" after.Name after.Age
// defining an interface as required, I won't buck the trend.
// Maybe this problem should be named "Use serialization features" instead
// of "Implement and use an Interface"
open System
open System.IO
open System.Runtime.Serialization.Formatters.Binary
[<Serializable>]
type Person(name:string, age:int) =
member this.Name = name
member this.Age = age
let serialize x =
use ms = new MemoryStream()
let bf = new BinaryFormatter()
bf.Serialize(ms, x)
ms.ToArray()
let deserialize<'a> bytes =
use ms = new MemoryStream(bytes:byte[])
let bf = new BinaryFormatter()
bf.Deserialize(ms) :?> 'a
let before = Person("Joel", 35)
let bytes = serialize before
let after = deserialize<Person> bytes
printfn "Before: %s, %i" before.Name before.Age
printfn "After: %s, %i" after.Name after.Age
fantom
@Serializable
class Person
{
Str name
Int age
new make(|This| f) { f(this) }
}
person := Person() { name="Tom Bones"; age=23 }
File(`tommy.dump`).out.writeObj(person).close
Person tom := File(`tommy.dump`).in.readObj
class Person
{
Str name
Int age
new make(|This| f) { f(this) }
}
person := Person() { name="Tom Bones"; age=23 }
File(`tommy.dump`).out.writeObj(person).close
Person tom := File(`tommy.dump`).in.readObj
java
// Serialization to a file
class Person implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private int age;
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public boolean equals(Object obj) {
if(obj == this) return true;
if(obj instanceof Person) {
Person p = (Person) obj;
return (p.getName().equals(this.getName())
& p.getAge() == this.getAge());
}
return false;
}
public String toString() {
return "Name: " + name + ", age: " + age;
}
}
Person person = new Person();
person.setName("Gaylord Focker");
person.setAge(21);
try {
File file = new File("ser.obj");
FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(person);
oos.close();
FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);
Person deserializedPerson = (Person) ois.readObject();
ois.close();
System.out.println(deserializedPerson);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
class Person implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private int age;
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public boolean equals(Object obj) {
if(obj == this) return true;
if(obj instanceof Person) {
Person p = (Person) obj;
return (p.getName().equals(this.getName())
& p.getAge() == this.getAge());
}
return false;
}
public String toString() {
return "Name: " + name + ", age: " + age;
}
}
Person person = new Person();
person.setName("Gaylord Focker");
person.setAge(21);
try {
File file = new File("ser.obj");
FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(person);
oos.close();
FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);
Person deserializedPerson = (Person) ois.readObject();
ois.close();
System.out.println(deserializedPerson);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
cpp
struct person
{
person(){}
person(const string &name, int age) : name_(name), age_(age) {}
string name_;
int age_;
template<typename Archive>
void serialize(Archive &ar, const unsigned int version) {
ar & name_ & age_;
}
};
int main()
{
const char *fn = "filename.txt";
person k("Ken", 38);
{
ofstream ofs(fn);
archive::text_oarchive oa(ofs);
oa << k;
}
person restored_person;
{
ifstream ifs(fn);
archive::text_iarchive ia(ifs);
ia >> restored_person;
}
cout << "Name : " << restored_person.name_ << endl
<< "Age : " << restored_person.age_ << endl;
}
{
person(){}
person(const string &name, int age) : name_(name), age_(age) {}
string name_;
int age_;
template<typename Archive>
void serialize(Archive &ar, const unsigned int version) {
ar & name_ & age_;
}
};
int main()
{
const char *fn = "filename.txt";
person k("Ken", 38);
{
ofstream ofs(fn);
archive::text_oarchive oa(ofs);
oa << k;
}
person restored_person;
{
ifstream ifs(fn);
archive::text_iarchive ia(ifs);
ia >> restored_person;
}
cout << "Name : " << restored_person.name_ << endl
<< "Age : " << restored_person.age_ << endl;
}
