Overview

Object Oriented Programming

Inheritance and Polymorphism

Source Code

<?pas
// Object Oriented Programming: Inheritance and Polymorphism

type
  TShape = class
    function Area : Float; virtual; abstract;
    function Name : String; virtual; abstract;
  end;

type
  TCircle = class(TShape)
    Radius : Float;
    constructor Create(r : Float); begin Self.Radius := r; end;
    function Area : Float; override; begin Result := PI * Radius * Radius; end;
    function Name : String; override; begin Result := 'Circle'; end;
  end;

type
  TSquare = class(TShape)
    Side : Float;
    constructor Create(s : Float); begin Self.Side := s; end;
    function Area : Float; override; begin Result := Side * Side; end;
    function Name : String; override; begin Result := 'Square'; end;
  end;

// Polymorphism in action
var shapes : array of TShape;
shapes.Add(new TCircle(5));
shapes.Add(new TSquare(4));
shapes.Add(new TCircle(2.5));

for var s in shapes do
   PrintLn(Format(
     'Shape: %s, Area: %.2f',
     [ s.Name, s.Area ]
   ));
?>

Result

Shape: Circle, Area: 78.54
Shape: Square, Area: 16.00
Shape: Circle, Area: 19.63
On this page