Overview

Object-Oriented Programming (OOP)

A comprehensive introduction to class-based design and polymorphism. This example explores defining class hierarchies, using 'virtual' and 'abstract' methods to define extensible interfaces, overriding constructors, and managing heterogeneous object collections using dynamic arrays of base class references.

Source Code

<?pas
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