Sub topic 12
Polymorphism: Coding Against an Interface Type
This chapter assumes you can write basic Apex classes and know how to declare an interface and implement it (covered in the previous chapters). It also assumes you are comfortable with List and Map. Here you will learn how one variable type can hold many different classes, how Apex picks the method to run, and where this pattern goes wrong.
What polymorphism means in Apex
Polymorphism means "many forms." In Apex, it means a variable declared with one type (an interface or a parent class) can hold an object of any class that implements or extends that type. When you call a method on the variable, Apex runs the version that belongs to the actual object.
Two types matter here:
- The declared type is the type written in the variable declaration, such as
Discount d. - The runtime type is the class of the object the variable points to, such as
PercentDiscount.
The compiler checks your code against the declared type. At run time, Apex looks at the runtime type to decide which method body to execute. This lookup is called dynamic dispatch.
Discount d = new PercentDiscount(10);
System.debug(d.apply(100)); // 90, PercentDiscount.apply runs
d = new FlatDiscount(5);
System.debug(d.apply(100)); // 95, FlatDiscount.apply runsThe call d.apply(100) is written the same way both times. Only the object changes.
Programming to an interface
"Coding against an interface" means your calling code mentions only the interface type, never the concrete classes. Compare two versions of a price calculator.
public class PriceCalculator {
private final List<Discount> discounts;
public PriceCalculator(List<Discount> discounts) {
this.discounts = discounts;
}
public Decimal finalPrice(Decimal base) {
Decimal price = base;
for (Discount d : discounts) {
price = d.apply(price);
}
return price;
}
}
// Usage
PriceCalculator calc = new PriceCalculator(new List<Discount>{
new PercentDiscount(10),
new FlatDiscount(5)
});
System.debug(calc.finalPrice(100)); // 85PriceCalculator never names PercentDiscount or FlatDiscount. You can add a LoyaltyDiscount class later without editing PriceCalculator. The calculator is open to new behavior and closed to changes.
This also makes testing easier. A test can pass in a small stub class instead of a real implementation:
@IsTest
private class PriceCalculatorTest {
private class ZeroDiscount implements Discount {
public Decimal apply(Decimal amount) {
return amount;
}
}
@IsTest
static void noDiscountKeepsPrice() {
PriceCalculator calc = new PriceCalculator(
new List<Discount>{ new ZeroDiscount() }
);
System.assertEquals(100, calc.finalPrice(100));
}
}The stub is an inner class, so it stays inside the test and does not clutter the org.
Polymorphism with a class hierarchy
Inheritance gives the same effect. A variable of the parent type can hold any child object, and overridden methods dispatch to the child.
List<Shape> shapes = new List<Shape>{
new Rectangle(3, 4),
new Rectangle(2, 5)
};
for (Shape s : shapes) {
System.debug(s.describe());
}Only methods that are virtual, abstract, or already override can be replaced by a child. A plain method has no dispatch: it always runs the version from the declared class.
Interface or parent class?
| Question | Interface | Parent class |
|---|---|---|
| Can a class use several? | Yes, `implements A, B` | No, one `extends` only |
| Can it share code and fields? | No, only method signatures | Yes |
| Must the parent be marked for extension? | Not applicable | Yes, `virtual` or `abstract` |
| Best for | A contract between unrelated classes | Related classes with shared logic |
A common approach is to define an interface for the contract and offer an abstract base class that implements it with shared helpers. Callers still depend only on the interface.
Casting and `instanceof`
Sometimes you hold a Discount and need something only PercentDiscount has. Apex lets you test the runtime type and cast to it.
Discount d = new PercentDiscount(10);
if (d instanceof PercentDiscount) {
PercentDiscount p = (PercentDiscount) d;
System.debug('Percent discount');
}An unchecked cast to the wrong type throws a System.TypeException. Use instanceof first if you are not sure.
Treat frequent instanceof checks as a warning sign. If the calling code branches on the concrete class, the interface is probably missing a method. Move the behavior into the interface and let dispatch do the work.
Selecting an implementation at run time
Polymorphism pays off when the implementation is chosen by data. A factory method is a static method that returns the interface type.
public class DiscountFactory {
public static Discount forCode(String code) {
if (code == 'TEN') {
return new PercentDiscount(10);
}
if (code == 'FIVE_OFF') {
return new FlatDiscount(5);
}
throw new IllegalArgumentException('Unknown code: ' + code);
}
}
// Usage
Discount d = DiscountFactory.forCode('TEN');
System.debug(d.apply(200)); // 180Here static and instance members work together. The static factory decides which object to build. The instance method apply carries the behavior. The only place that knows the concrete class names is the factory.
Apex also supports Type.forName and Type.newInstance to create an object from a class name stored in a string or custom metadata. This is how many Salesforce frameworks let admins plug in classes without code changes.
Type t = Type.forName('PercentDiscount');
Discount d = (Discount) t.newInstance();newInstance requires a public or global no-argument constructor. PercentDiscount as written takes a Decimal, so that snippet would fail with a runtime exception unless you add a no-argument constructor. The compiler cannot catch this, because the class name is only a string.
Common errors and gotchas
Calling a method that is not on the declared type
The compiler checks the declared type. This fails even though the object has the method:
Discount d = new PercentDiscount(10);
// d.setPercent(20); // compile error: method does not exist on DiscountEither cast to PercentDiscount or add the method to the interface.
Forgetting `public` on the implementing method
Interface methods have no access modifier, but the implementing methods must be at least as visible as the interface. A private or missing modifier on apply in PercentDiscount is a compile error.
Missing `override`
When a child redefines a virtual method, the keyword override is required. Methods that implement an interface method do not use override. Mixing these up is a frequent compile error.
Null elements
A List<Discount> can hold null. Calling d.apply(price) on a null element throws a System.NullPointerException, not a polymorphism error. Validate input when you accept a list from outside.
Collections are not covariant in every case
A List<PercentDiscount> can be assigned to a List<Discount> in Apex, but the reverse needs a cast, and mixing types in one list is easy to get wrong. Build the list as List<Discount> from the start when you want mixed implementations.
Fields are not dispatched
Dynamic dispatch applies to methods only. If a parent and child both declare a field with the same name, the declared type decides which one you read. Avoid redeclaring fields in child classes and use methods when behavior must vary.
Trade-offs
- Indirection. Readers must find which classes implement the interface. Keep interfaces small, with one clear purpose.
- Cost. Dispatch has no meaningful effect on governor limits. Extra classes count toward the org's code size limit, though.
- Over-design. An interface with a single implementation and no test stub or planned second class often adds files without value. Wait until a second implementation exists or a test needs a stub.
Exercise
A method Decimal total(List<Discount> ds, Decimal base) contains if (ds[0] instanceof FlatDiscount) { ... } else { ... } to handle each type differently. What is the design problem, and how would you fix it?
Show answer
The calling code depends on concrete classes, so each new Discount class forces an edit here. The differing behavior should be a method on the Discount interface, with each class implementing its own version. The caller then calls that method on the interface type and Apex dispatches to the right class.
Exercise
You call Type.forName('PercentDiscount').newInstance() and get a runtime exception, although the class compiles. What is the likely cause?
Show answer
The class has only a constructor with parameters. newInstance needs a public or global constructor with no arguments, and this is only checked at run time. Add a no-argument constructor.