Polymorphism is a feature of object-oriented programming languages that allows different objects to respond to the same method call in different ways. In Delphi, polymorphism is implemented using virtual methods and overriding.
Here is an example of polymorphism in Delphi:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
type TShape = class public procedure Draw; virtual; abstract; end; TCircle = class(TShape) public procedure Draw; override; end; TRectangle = class(TShape) public procedure Draw; override; end; procedure TShape.Draw; begin // Default implementation for drawing a shape end; procedure TCircle.Draw; begin // Implementation for drawing a circle end; procedure TRectangle.Draw; begin // Implementation for drawing a rectangle end; var Shape: TShape; begin Shape := TCircle.Create; Shape.Draw; Shape.Free; Shape := TRectangle.Create; Shape.Draw; Shape.Free; end; |
In this example, the TShape
class has an abstract Draw
method that must be overridden by derived classes. The TCircle
and TRectangle
classes both override the Draw
method to provide their own implementation for drawing the shape.
When the Draw
method is called on a TShape
object, the implementation from the most derived class is used. For example, when Shape.Draw
is called on a TCircle
object, the TCircle.Draw
method is called. When Shape.Draw
is called on a TRectangle
object, the TRectangle.Draw
method is called.
This allows different objects to respond to the same method call in different ways, depending on their specific type. Polymorphism is a powerful feature that can be used to create flexible and reusable code.
Leave a Reply