Sub topic 12
Polymorphism: coding against an interface type
This chapter assumes you can already declare an interface and write a class that implements it. It also assumes you know what virtual and override mean. Here the focus is on what you gain by writing code that depends on the interface type instead of a concrete class.
What polymorphism means in Apex
Polymorphism means one variable type can hold objects of many different classes. A variable declared as Discount can refer to a PercentDiscount, a FlatDiscount, or any future class that implements Discount. When you call d.apply(100), Apex looks at the actual object at runtime and runs that class's method. This is called dynamic dispatch.
Writing code against the interface
The service below never mentions PercentDiscount or FlatDiscount. It only knows the contract.
// Discount.cls
public interface Discount {
Decimal apply(Decimal amount);
}
// PercentDiscount.cls
public class PercentDiscount implements Discount {
private final Decimal percent;
public PercentDiscount(Decimal percent) {
this.percent = percent;
}
public Decimal apply(Decimal amount) {
return amount - (amount * percent / 100);
}
}
// FlatDiscount.cls
public class FlatDiscount implements Discount {
private final Decimal off;
public FlatDiscount(Decimal off) {
this.off = off;
}
public Decimal apply(Decimal amount) {
return amount - off;
}
}
// PricingService.cls
public class PricingService {
public static Decimal finalPrice(Decimal base, List<Discount> discounts) {
Decimal price = base;
for (Discount d : discounts) {
price = d.apply(price);
}
return price;
}
}
// Usage
List<Discount> discounts = new List<Discount>{
new PercentDiscount(10),
new FlatDiscount(5)
};
System.debug(PricingService.finalPrice(100, discounts)); // 85To add a new kind of discount, you write one new class that implements Discount. PricingService does not change. This is the main benefit: new behavior arrives without edits to working code.
Apex tests benefit too. A test can pass a small stub class that implements the interface, so it does not need real data or callouts.
Common errors
- Calling a method the interface does not declare. The compiler checks the declared type, not the object. If
PercentDiscounthas agetPercent()method,d.getPercent()fails to compile whendis aDiscount. - Casting without checking. A cast to the wrong class throws a
System.TypeExceptionat runtime. Test withinstanceoffirst:
Discount d = new FlatDiscount(5);
if (d instanceof PercentDiscount) {
PercentDiscount p = (PercentDiscount) d;
System.debug('Percent discount');
} else {
System.debug('Not a percent discount'); // runs
}- Expecting static methods to be polymorphic. Dispatch applies to instance methods only. A static method is chosen by the class name you write, so it cannot be swapped through an interface.
- Passing null. A
nullentry in the list compiles fine. It throws aSystem.NullPointerExceptionwhend.applyruns.
Interface or base class?
Both support polymorphism. An interface only declares a contract. A class can implement many interfaces but extend only one class. Use a virtual or abstract base class when subclasses share real code or fields. Otherwise, prefer the interface.
Exercise
A method has the parameter Discount d, and you pass it new FlatDiscount(5). FlatDiscount also has a public method getOff(). Why does d.getOff() fail to compile, and how can you call it safely?
Show answer
The compiler checks the declared type Discount, which has no getOff() method, even though the object is a FlatDiscount. To call it, check d instanceof FlatDiscount and then cast: ((FlatDiscount) d).getOff(). Alternatively, add getOff() to the interface if every implementation can support it.