View Category
OOP

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.
ruby
class Greeter
def initialize(whom) @whom = whom end
def greet() puts "Hello, #{@whom}!" end
end

(Greeter.new("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();
}
}
perl
{ package Greeter;
sub new {
my $self = {};
my $type = shift;
$self->{'whom'} = shift;
bless $self, $type;
}

sub greet {
my $self = shift;
print "Hello " . $self->{'whom'} . "!\n";
}
}

my $greeter = Greeter->new("world");
$greeter->greet();
{
package Greeter;

sub new {
my $class = shift;
my $whom = shift or die 'Need a name to greet';
bless \$whom, $class;
}

sub greet {
my $self = shift;
print "Hello $$self!\n";
}
}

my $greeter = Greeter->new("Bob");
$greeter->greet();
groovy
// version using named parameters
class Greeter {
def whom
def greet() { println "Hello, $whom" }
}
new Greeter(whom:'world').greet()
// version using traditional constructor
class Greeter {
private whom
Greeter(whom) { this.whom = whom }
def greet() { println "Hello, $whom" }
}
new Greeter('world').greet()
scala
class Greeter(whom : String) { def greet() = { printf("Hello %s\n", whom) } }

(new Greeter("world!")).greet()
python
class Greeter(object):
""" Greet someone.
"""
def __init__(self, whom):
self._whom = whom
def greet(self):
print "Hello, %s!" % self._whom

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 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);
}
fsharp
type Greeter(whom' : string) =
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()
type Greeter =
class
val whom : string
new(whom') = { whom = whom' }
member this.greet() = printfn "Hello, %s!" this.whom
end

(new Greeter("world")).greet()
erlang
Greeter = make_greeter("world!"),
Greeter(greet).
ocaml
class greeter message =
object
method greet = print_endline message
end

let o = new greeter "Hello" in
o#greet
csharp
using System;

class Greeter
{
private string name {get;set;}

public void Greet(){
Console.WriteLine("Hello, {0}",name);
}

public Greeter(string name){
this.name = name;
}
}

class Test
{
static void Main()
{
new Greeter("Dante").Greet();
}
}
php
class Greeter {
private $whom;
public function __construct($whom) {
$this->whom = $whom;
}
public function greet() {
echo "Hello $this->whom.";
}
}
$g = new Greeter("Giacomo Girolamo");
$g->greet();
haskell
data Greeter = Greeter String

class Greets a where
greet :: a -> IO ()

instance Greets Greeter where
greet (Greeter s) = print s

main = greet (Greeter "Hello")
clojure
(defprotocol IGreeter
(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"))
fantom
class Greeter
{
private Str whom
new make(Str whom) { this.whom = whom }
Void greet() { echo("Hello, $whom") }
}

Greeter("world").greet
go
type Greeter struct {
whom string
}

func (g Greeter) greet() {
fmt.Printf("Hello %s\n", g.whom)
}

func main() {
Greeter{"world"}.greet()
}

Instantiate object with mutable state

Reimplement the Greeter class so that the '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.
ruby
class Greeter
attr_accessor :whom
def initialize(whom) @whom = whom end
def greet() puts "Hello, #{@whom}!" end
end

greeter = Greeter.new("world") ; greeter.greet()

greeter.whom = 'Tommy' ; greeter.greet()
puts "I have just greeted %s" % 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() + ".");
perl
package Greeter;
sub new {
my ($class, $whom) = @_;
bless {whom => $whom}, $class;
}
sub whom {
my ($self, $whom) = @_;
if ($whom) { $self->{whom} = $whom; }
else { return $self->{whom} }
}
sub greet {
my ($self) = @_;
my $whom = $self->{whom};
print "Hello, $whom!\n";
}
package main;

my $g = new Greeter ("world");
$g->greet;

$g->whom("Tommy");
$g->greet;
print "I have just greeted " . $g->whom . "\n";
groovy
class Greeter {
def whom
def greet() { println "Hello, $whom!" }
}

greeter = new Greeter(whom:"world"); greeter.greet()

greeter.whom = 'Tommy'; greeter.greet()
println "I have just greeted $greeter.whom"
scala
class Greeter(var whom: String) {
def greet() = println("Hello " + whom + "!")
}

// Is this really a private value with getter and setter methods,
// or just a public mutable value?

val greeter = new Greeter("World")
greeter.greet()
greeter.whom = "Tommy"
greeter.greet()
printf("I have just greeted %s.\n", greeter.whom)
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()
# 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()
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;
}
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
ocaml
class greeter =
object
val mutable whom = "someone"
method set_whom greetee = whom <- greetee
method get_whom = whom
method greet = Printf.printf "Hello, %s!\n" whom
end;;

let o = new greeter in
o#set_whom "Tommy";
o#greet;
Printf.printf "I have just greeted %s.\n" o#get_whom
csharp
class Greeter
{
public string Name {get;set;}

public void Greet(){
Console.WriteLine("Hello, {0}",Name);
}

public Greeter(string name){
this.Name = name;
}

// Driver
public static void Main()
{
var g = new Greeter("Dante");

g.Name = "Tommy";
g.Greet();
Console.Write("I have just greated {0}", g.Name);
}
}
php
class Greeter {
private $whom;
public function __construct($whom) {
$this->whom = $whom;
}
public function greet() {
echo "Hello $this->whom.\n";
}
public function getWhom() {
return $this->whom;
}
public function setWhom($whom) {
$this->whom = $whom;
}
}
$g = new Greeter("Giacomo Girolamo");
$g->greet();
$g->setWhom("Jean-Jaques");
$g->greet();
echo "I have just greeted " . $g->getWhom() . ".\n";
haskell
data Greeter = G { greeting :: String, greetee :: String }

class Greets a where
greet :: a -> IO ()

instance Greets Greeter where
greet g = print (greeting g)

main = do
let g = G { greeting = "Hello", greetee = "{whom}" }
greet g
print $ "I have just greeted " ++ greetee g { greetee = "Tommy" }
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)))
"."))
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}.")

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 '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.
ruby
class Shape
def initialize(name="") @name = name end
end

class Circle < Shape
def initialize(radius) super("circle") ; @radius = radius end

def area() 3.14159 * @radius * @radius end
def circumference() 2 * 3.14159 * @radius end

def print()
puts "I am a #{@name} with ->"
puts "Radius: %.2f" % @radius
puts "Area: %.2f" % self.area()
puts "Circumference: %.2f\n" % self.circumference()
end

end

class Rectangle < Shape
def initialize(length, breadth) super("rectangle") ; @length = length ; @breadth = breadth end

def area() @length * @breadth end
def perimeter() 2 * @length + 2 * @breadth end

def print()
puts "I am a #{@name} with ->"
printf("Length, Width: %.2f, %.2f\n", @length, @breadth)
puts "Area: %.2f" % self.area()
puts "Perimeter: %.2f\n" % self.perimeter()
end
end

# ------

shapes = [Circle.new(4.2), Rectangle.new(2.7, 3.1), Rectangle.new(6.2, 2.6), Circle.new(17.3)]
shapes.each {|shape| shape.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();
perl
package Shapes;

use MooseX::Declare;

class Shape {
use MooseX::ABC;
requires qw/area print/;
has 'name' => (is => 'ro', isa => 'Str', default => '', required => 0, init_arg => undef );

}

class Circle extends Shape {
use constant PI => 4 * atan2(1, 1);

has '+name' => ( default => 'circle' );
has 'radius' => (is => 'ro', isa => 'Num', required => 1, init_arg => 'r' );

sub area { PI * ( $_[0]->radius ** 2 ) }
sub circumference { 2 * PI * ( $_[0]->radius ** 2 ) }

sub print {
my $self = shift;

printf <<"END_OF_BLOCK", map { $self->$_ } qw/name radius area circumference/;
I am a '%s' with
Radius: %.2f
Area: %.2f
Circumference: %.2f
END_OF_BLOCK

}

}

class Rectangle extends Shape {

has '+name' => ( default => 'rectangle' );
has 'length' => (is => 'ro', isa => 'Num', required => 1, init_arg => 'l' );
has 'breadth' => (is => 'ro', isa => 'Num', required => 1, init_arg => 'b' );

sub area { $_[0]->length * $_[0]->breadth }
sub perimeter { 2 * ( $_[0]->length + $_[0]->breadth ) }

sub print {
my $self = shift;

printf <<"END_OF_BLOCK", map { $self->$_ } qw/name length breadth area perimeter/;
I am a '%s' with
Length, Width: %.2f, %.2f
Area: %.2f
Perimeter: %.2f
END_OF_BLOCK

}

}

1;

package main;

my @shapes = ( Circle->new( r => 4.2 ), Rectangle->new(l => 2.7, b => 3.1),
Rectangle->new(l => 6.2, b => 2.6), Circle->new( r => 17.3) );
$_->print for @shapes;
{
package Shapes;

sub new {
my $class = shift;
die 'Invalid parameters' if (@_ % 2);
my %parameters = @_;
die 'Missing name' unless defined $parameters{name};
bless \%parameters, $class
}

sub area {
die
'area() method must be implemented by ',__PACKAGE__.' subclasses';
}
sub print {
my $self = shift;
printf "Name: \t%s\n", $self->{name};
printf "Area: \t%.2f\n", $self->area();
}
}

{
package Circle;
use parent -norequire, 'Shapes';
use Scalar::Util qw/looks_like_number/;
use Math::Trig;

sub new {
my $class = shift;
my $self = $class->SUPER::new(name => 'Circle', @_);
die 'Missing radius' unless defined($self->{radius});
die 'Invalid radius (not a number)'
unless looks_like_number($self->{radius});
$self
}
sub area {
my $self = shift;
pi * ($self->{radius} ** 2)
}
sub circumference {
my $self = shift;
2 * pi * $self->{radius};
}
sub print {
my $self = shift;
$self->SUPER::print;
printf "Circumference: \t%.2f\n", $self->circumference;
}

}

{
package Rectangle;
use parent -norequire, 'Shapes';
use Scalar::Util qw/looks_like_number/;

sub new {
my $class = shift;
my $self = $class->SUPER::new(name => 'Rectangle', @_);
do {
die "Missing $_" unless defined($self->{$_});
die "Invalid $_" unless looks_like_number($self->{$_});
} for qw/length breadth/;
$self;
}
sub area {
my $self = shift;
$self->{length} * $self->{breadth}
}
sub print {
my $self = shift;
$self->SUPER::print();
do {
printf ucfirst($_).": \t%.2f\n", $self->{$_}
} for qw/length breadth/;
}
}


package main;

my @shapes = ( Circle->new( radius => 4.2 ),
Rectangle->new(length => 2.7, breadth => 3.1),
Rectangle->new(length => 6.2, breadth => 2.6),
Circle->new( radius => 17.3) );
$_->print for @shapes;
groovy
abstract class Shape {
final name
Shape(name) { this.name = name }
abstract area()
abstract print()
}

class Circle extends Shape {
final radius
Circle(radius) {
super('circle')
this.radius = radius
}
def area() { Math.PI * radius * radius }
def circumference() { 2 * Math.PI * radius }
def print() {
println "I am a $name with ->"
printf 'Radius: %.2f\n', radius
printf 'Area: %.2f\n', area()
printf 'Circumference: %.2f\n', circumference()
}
}

class Rectangle extends Shape {
final length, breadth
def Rectangle(length, breadth) {
super("rectangle")
this.length = length
this.breadth = breadth
}
def area() { length * breadth }
def perimeter() { 2 * length + 2 * breadth }
def print() {
println "I am a $name with ->"
printf 'Length, Width: %.2f, %.2f\n', length, breadth
printf 'Area: %.2f\n', area()
printf 'Perimeter: %.2f\n', perimeter()
}
}

shapes = [new Circle(4.2), new Rectangle(2.7, 3.1), new Rectangle(6.2, 2.6), new Circle(17.3)]
shapes.each { shape -> shape.print() }
scala
abstract class Shape (val name: String) {
def area : Double
def print()
}

class Circle (val radius: Double) extends Shape("Circle") {
def area = Math.Pi * radius * radius
def circumference = 2 * Math.Pi * radius
def print() {
println("I'm a " + name + " with")
printf(" * radius = %.2f\n", radius)
printf(" * area = %.2f\n", area)
printf(" * circumference = %.2f\n\n", circumference)
}
}

class Rectangle (val length: Double, val breadth: Double) extends Shape("Rectangle") {
def area = length * breadth
def perimeter = 2 * (length + breadth)
def print() {
println("I'm a " + name + " with")
printf(" * length = %.2f\n", length)
printf(" * breadth = %.2f\n", breadth)
printf(" * area = %.2f\n", area)
printf(" * perimeter = %.2f\n\n", perimeter)
}
}

val shapes = List(new Circle(5.4), new Rectangle(7.8, 6.5))
shapes foreach (_.print)
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_()
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();
}
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()
ocaml
class virtual shape =
object(self)
method name = "shape"
method virtual area : float
method print = Printf.sprintf "%s, area %f" self#name self#area
end ;;

let pi = 4. *. atan 1.

class circle radius =
object(self)
inherit shape as super
method name = "circle"
method area = radius *. radius *. pi
method circumference = radius *. 2. *. pi
method print = Printf.sprintf "%s, circumference %f" super#print self#circumference
end

class rectangle length breadth =
object(self)
inherit shape as super
method name = "rectangle"
method area = length *. breadth
method perimeter = 2. *. ( length +. breadth)
method print = Printf.sprintf "%s, perimeter %f" super#print self#perimeter
end

let c = new circle 5. in
let r = new rectangle 7. 3. in
print_endline c#print;
print_endline r#print
csharp
// While abstract classes do exist in C#, it is most common to use
// an interface in this type of situation.
// It is a common idiom to prefix interface names with an I
public interface IShape {
string Name { get; }
double Area { get; }
void Print();
}

public class Circle : IShape {

private double Radius { get; set; }
public Circle(double radius) {
Name = "Circle";
Radius = radius;
}

public string Name { get; private set; }
public double Area {
get {
return Math.PI * Radius * Radius;
}
}
public double Circumference {
get {
return Math.PI * (Radius + Radius);
}
}

public void Print() {
Console.WriteLine( " Name: {0}\n Area: {1}\n Circumference: {2}\n Radius: {3}",
this.Name,
this.Area,
this.Circumference,
this.Radius
);
}
}

public class Rectangle : IShape {

private double Length { get; set; }
private double Breadth { get; set; }
public Rectangle(double length, double breadth) {
Name = "Rectangle";
Length = length;
Breadth = breadth;
}

public string Name { get; private set; }
public double Area {
get {
return Length * Breadth;
}
}
public double Perimeter {
get {
return (Length * 2) + (Breadth * 2 );
}
}

public void Print() {
Console.WriteLine( " Name: {0}\n Area: {1}\n Perimeter: {2}\n Length: {3}\n Breadth: {4}",
this.Name,
this.Area,
this.Perimeter,
this.Length,
this.Breadth
);
}
}

// Driver
public class InheritanceHeirarchy {
public static void _Main() {
var c = new Circle(2.1);
c.Print();

Console.WriteLine();

var r = new Rectangle(2.2, 3.3);
r.Print();
}
}
php
<?php
abstract class Shape
{
protected $name;
abstract public function area ();
abstract public function _print ();
public function __construct ($name)
{
$this->name = $name;
}
}

class Circle extends Shape
{
protected $radius;
public function __construct ($radius)
{
parent::__construct('Circle');
$this->radius = $radius;
}
public function area ()
{
return pi() * $this->radius * $this->radius;
}
public function circumference ()
{
return 2 * pi() * $this->radius;
}
public function _print ()
{
print("I am a {$this->name} with ->\n");
print(" Radius: {$this->radius}\n");
print(" Area: {$this->area()}\n");
print(" Circumference {$this->circumference()}\n");
}
}

class Rectangle extends Shape
{
protected $length;
protected $breadth;
public function __construct ($length, $breadth)
{
parent::__construct('Rectangle');
$this->length = $length;
$this->breadth = $breadth;
}
public function area ()
{
return $this->length * $this->breadth;
}
public function perimeter ()
{
return (2 * $this->length) + (2 * $this->breadth);
}
public function _print ()
{
print("I am a {$this->name} with ->\n");
print(" Length, Width: {$this->length}, {$this->breadth}\n");
print(" Area: {$this->area()}\n");
print(" Perimeter: {$this->perimeter()}\n");
}
}

$shapes = array(new Circle(4.2) , new Rectangle(2.7, 3.1) , new Rectangle(6.2, 2.6) , new Circle(17.3));

foreach ($shapes as $shape) {
$shape->_print();
}
haskell
data Circle = C { namec :: String, radius :: Float }
data Rectangle = R { namer :: String, len :: Float, breadth :: Float }

circumference (C _ r) = 2 * pi * r
perimeter (R _ l b) = 2 * (l + b)

class Shape a where
area :: a -> Float
name :: a -> String
println :: a -> IO ()

instance Shape Circle where
area (C _ r) = pi * r * r
println c = print $ namec c ++ " : area = " ++
show (area c) ++ ", radius = " ++
show (radius c)
name (C n _) = n

instance Shape Rectangle where
area (R _ l b) = l * b
println r = print $ namer r ++ " : area = " ++
show (area r) ++ ", length = " ++
show (len r) ++ ", breadth = " ++
show (breadth r)
name (R n _ _) = n

main = do
let c = C { namec = "Circle", radius = 2.34 }
r = R { namer = "Rectangle", len = 3.4, breadth = 2.456 }
println c
println r
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)))
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

Implement and use an Interface

Create a Serializable interface consisting of '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.
ruby
class Person
def initialize(name, age)
@name, @age = name, age
end
end

tom = Person.new("Tom Bones", 23)

File.open('tommy.dump', 'w+') {|f| f.write(Marshal.dump(tommy)) }
toms_clone = Marshal.load(File.read('tommy.dump'))
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();
}
perl
package Person;

use Moose;
use MooseX::Storage;
with Storage('format' => 'JSON', 'io' => 'File');

has 'name' => (is => 'rw', isa => 'Str');
has 'age' => (is => 'rw', isa => 'Int');

1;

Person->new( name => 'David B.', age => 28)->store('person.json');

my $p = Person->load('person.json');
{
package Serializable;
use Role::Basic;
use Storable qw'store_fd retrieve_fd';
use Scalar::Util 'blessed';
use IO::Handle;
use Carp;

sub save {
my $self = shift;
my $fd = shift or croak 'Needs target file handle';
$DB::single = (1);
store_fd($self, $fd);
}

sub restore {
my $class = shift;
my $fd = shift or croak 'Needs source file handle';
my $self = retrieve_fd( $fd );
bless $self, $class
}

}
{
package Person;
use Role::Basic 'with';
use Scalar::Util 'looks_like_number';
use Carp;

with 'Serializable';

sub new {
my $class = shift;
croak 'Invalid parameters' if (@_ % 2);
%parameters = @_;

do {
croak "Missing $_" unless defined $parameters{$_}
} for qw/name age/;
croak 'Invalid age' unless looks_like_number($parameters{age});
bless \%parameters, $class
}
sub name {
$self{name}
}
sub age {
$self{age}
}
}

use IO::Handle;
my $p1 = Person->new(age => 42, name => 'Milly Fogg');
open my $fh, '+>', 'person.store';
$p1->save( $fh );
seek $fh, 0, SEEK_SET;
my $p2 = Person->restore( $fh );
groovy
// Built-in functionality but with slightly different names. Showing usage:
class Person implements Serializable { String name; int age }
p1 = new Person(name:'John', age:21)
p2 = null
output = new ByteArrayOutputStream() // or FileOutputStream, etc.
output.withObjectOutputStream { oos -> oos << p1 }
input = new ByteArrayInputStream(output.toByteArray())
input.withObjectInputStream(getClass().classLoader){ ois -> p2 = ois.readObject() }
assert p2.name == 'John'
assert p2.age == 21
scala
class Person (var name: String, var age: Int) extends Serializable

val p1 = new Person("John", 21)
val output = new ByteArrayOutputStream()
val oos = new ObjectOutputStream(output)
oos.writeObject(p1)
oos.flush
oos.close

val input = new ByteArrayInputStream(output.toByteArray())
val ois = new ObjectInputStream(input)
val p2 = ois.readObject().asInstanceOf[Person]

assert(p2.name == "John")
assert(p2.age == 21)
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)
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;
}
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
ocaml
(* in OCaml, interfaces are class types, and have nothing to do with inheritance,
so I'm not sure what's the correct answer to this problem (if any) *)

class type serializable =
object
method save: out_channel -> unit
method restore: in_channel -> unit
end

class person name age =
object
val mutable my_name = name
val mutable my_age = age
method save oc = output_value oc my_name; output_value oc my_age
method restore ic = my_name <- input_value ic; my_age <- input_value ic
method print = Printf.printf "I'm %s, %d\n" my_name my_age
end

let transfer (o1: serializable) (o2: serializable) =
let temp_filename = "_person" in
let backing_store_save = open_out_bin temp_filename in
o1#save backing_store_save;
close_out backing_store_save;

let backing_store_restore = open_in_bin temp_filename in
o2#restore backing_store_restore;
close_in backing_store_restore


let o = new person "john" 42 in
let o2 = new person "nobody" 0 in
transfer (o :> serializable) (o2 :> serializable);
o2#print
php
class Person implements Serializable {
private $name;
private $age;
public function __construct($name, $age) {
$this->name = $name;
$this->age = $age;
}
public function serialize() {
return serialize(array($this->name, $this->age));
}
public function unserialize($serialized) {
list($this->name, $this->age) = unserialize($serialized);
}
public function getData() {
return array($this->name, $this->age);
}
}

$obj = new Person('Gaylord Focker', 21);
file_put_contents('person.dump', serialize($obj));

$newobj = unserialize(file_get_contents('person.dump'));

var_dump($newobj->getData());
haskell
import Data.Binary
import Control.Monad (liftM2)

data People = People { name :: String, age :: Integer }
deriving (Eq, Show)

class Serializable a where
save :: FilePath -> a -> IO ()
restore :: FilePath -> IO a

instance Serializable People where
save = encodeFile
restore = decodeFile

instance Binary People where
put (People n a) = put n >> put a
get = liftM2 People get get

main = do let fp = "people.dat"
p = People { name = "Joe", age = 24 }
save fp p
p' <- restore fp
print (p' :: People)
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))
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