Lesson 5 · 5 of 20
Abstract classes · Pascal
Declare abstract methods in Object Pascal to define a common outline that each child class fills in, with payment methods and their fees.

An `abstract` method is declared but not implemented: TPayment.Fee says every payment has a fee, but not which one. It must also be virtual, because its only purpose is to be completed by child classes with override.
TPayment is an abstract class: a template, not something to create objects from. If you wrote TPayment.Create, Free Pascal would compile it with a warning, and calling Fee would raise EAbstractError. The real objects are TCard (1.5 % of the amount) and TTransfer (a flat 0.35 EUR).
The interesting part is Charge: a regular method of the abstract class that uses the abstract one. Every payment is charged with the same steps and only the fee changes. This is the *template method* pattern: the parent sets the outline, the children supply the detail.
Copy(ClassName, 2, 9) drops the leading T from the class name to print Card or Transfer. The loop creates each payment method, charges it 20 and 250 EUR and frees it with Free.
Code · main.pas
program main;type TPayment = class function Fee(amount: Double): Double; virtual; abstract; // no body here procedure Charge(amount: Double); end; TCard = class(TPayment) function Fee(amount: Double): Double; override; end; TTransfer = class(TPayment) function Fee(amount: Double): Double; override; end;procedure TPayment.Charge(amount: Double);begin // the same steps for every method; only Fee changes WriteLn(Copy(ClassName, 2, 9):8, amount:8:2, ' + fee', Fee(amount):5:2, ' =', amount + Fee(amount):7:2);end;function TCard.Fee(amount: Double): Double;begin Result := amount * 0.015; // 1.5 % of the amountend;function TTransfer.Fee(amount: Double): Double;begin Result := 0.35; // flat feeend;var method: TPayment;begin for method in [TCard.Create, TTransfer.Create] do begin method.Charge(20); method.Charge(250); method.Free; end;end.Output · fpc main.pas && ./main
Card 20.00 + fee 0.30 = 20.30
Card 250.00 + fee 3.75 = 253.75
Transfer 20.00 + fee 0.35 = 20.35
Transfer 250.00 + fee 0.35 = 250.35Key points
virtual; abstract;declares a method with no body.- An abstract class is a template; you use its children.
- Calling an abstract method raises
EAbstractError. - Regular methods in the parent can call the abstract ones.
- Template method: shared steps, details in each child.
Exercise
Add TBizum = class(TPayment) with no fee for amounts up to 50 EUR and 0.20 EUR above that, and charge it the same two amounts.