Sub topic 10
Defining and implementing interfaces
This chapter assumes you can write basic Apex classes with fields, methods, and constructors. It also assumes you know how to use List and Map, and that you know access modifiers such as public and private. It covers the syntax for interfaces, the rules the compiler enforces, and the mistakes people most often make.
What an interface is
An interface is a named contract. It lists method signatures: the name, parameter types, and return type. It says nothing about how those methods work. Any class that declares implements for the interface must supply a body for every method.
Code that depends on the interface does not care which class sits behind it. You can swap implementations without changing the caller.
An interface is a type. You can declare variables, parameters, return types, and collection element types with it. You cannot create one with new, because it has no behavior of its own.
Declaring an interface
// Discount.cls
public interface Discount {
Decimal apply(Decimal amount);
}The rules for the body are strict:
- Methods have a signature and a semicolon, with no body.
- Methods have no access modifier. Writing
publicorprivateon an interface method is a compile error. - There are no fields, constants, constructors, or static methods.
- The interface itself has a visibility,
publicorglobal. Apublicinterface is visible inside your namespace. Aglobalinterface can be used outside it, such as in a managed package. A global interface needs global methods in its implementations.
Each interface is usually saved in its own file, named after the interface, such as Discount.cls.
Implementing an interface
A class declares the contract with implements:
// 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;
}
}The implementing method must match the interface method exactly in these respects:
- The name is the same.
- The parameter types are the same, in the same order.
- The return type is the same.
- The method is
public(orglobal). An implementation of an interface method cannot beprivateorprotected, because the interface promises the method is callable from outside.
The diagram below shows the relationship.
Using the interface type
The benefit appears in the calling code. A List<Discount> can hold any mix of implementations:
List<Discount> discounts = new List<Discount>{
new PercentDiscount(10),
new FlatDiscount(5)
};
Decimal price = 100;
for (Discount d : discounts) {
price = d.apply(price);
}
System.debug(price); // 85The loop calls apply through the Discount type. At runtime, Apex runs the version belonging to the actual object. The next chapters on polymorphism return to this idea.
Passing an implementation in
A common use is to hand a class its collaborator through the constructor:
// CheckoutService.cls
public class CheckoutService {
private final Discount discount;
public CheckoutService(Discount discount) {
this.discount = discount;
}
public Decimal total(List<Decimal> prices) {
Decimal sum = 0;
for (Decimal p : prices) {
sum += p;
}
return discount.apply(sum);
}
}
// Usage
CheckoutService svc = new CheckoutService(new FlatDiscount(5));
System.debug(svc.total(new List<Decimal>{ 40, 60 })); // 95CheckoutService never mentions PercentDiscount or FlatDiscount. Adding a SeasonalDiscount later needs no change to this class.
This also makes tests easier. A test can pass in a trivial stand-in:
// NoDiscount.cls
@IsTest
public class NoDiscount implements Discount {
public Decimal apply(Decimal amount) {
return amount;
}
}The stand-in removes discount logic from the test, so a failure points at CheckoutService.
Multiple interfaces and interface inheritance
A class can implement several interfaces, separated by commas. It must satisfy all of them:
public interface Labeled {
String label();
}
public class SeasonalDiscount implements Discount, Labeled {
public Decimal apply(Decimal amount) {
return amount * 0.8;
}
public String label() {
return 'Seasonal';
}
}An interface can also extend another interface with extends:
public interface LabeledDiscount extends Discount {
String label();
}A class that implements LabeledDiscount must implement both label() and apply(Decimal). An object of that class can be used wherever a Discount is expected.
If two interfaces declare the same signature, one method in the class satisfies both. If they declare the same name and parameters with different return types, no class can implement both, and the compiler reports an error.
Checking and casting the type
Sometimes you hold a Discount and need to know the concrete class. Use instanceof and an explicit cast:
Discount d = new PercentDiscount(10);
if (d instanceof PercentDiscount) {
PercentDiscount p = (PercentDiscount) d;
// use members that only PercentDiscount has
}An invalid cast throws a System.TypeException. If you find yourself writing many instanceof checks, the interface is probably missing a method. Add the method to the contract and let each class supply its own behavior.
Interfaces compared with classes
| Feature | Interface | Class |
|---|---|---|
| Method bodies | No | Yes |
| Fields | No | Yes |
| Constructors | No | Yes |
| Create with `new` | No | Yes |
| Extend or implement several | Yes, a class can implement many interfaces | One parent class only |
| Method access modifier | None allowed | Required or defaulted |
The last two rows matter for design. A class can extend only one parent, but it can implement as many interfaces as it needs. Interfaces are the way to give unrelated classes a shared capability.
Common errors
- Missing a method. The compiler reports that the class must implement the method from the interface. Check that you implemented every method, including those inherited through
extends. - Wrong visibility. Declaring the implementation without
publicgives the method default (private) access, and the compiler rejects it. Always writepublicorglobal. - Modifiers on the interface method.
public Decimal apply(Decimal amount);inside an interface fails to compile. Leave the modifier out. - Mismatched signature. Changing
DecimaltoDouble, or the parameter count, makes it a different method. The interface method remains unimplemented. - Instantiating the interface.
new Discount()is invalid. Create an implementing class instead. - Global mismatch. A
globalinterface needsglobalimplementing methods, and the implementing class must beglobalas well.
Summary of rules
- An interface lists method signatures, with no bodies, fields, or constructors.
- Interface methods take no access modifier. Implementations must be
publicorglobal. - A class implements one or more interfaces with
implementsand must supply every method. - Interfaces can extend other interfaces.
- Variables, parameters, and collections can use the interface as their type.
- Use
instanceofand casts sparingly.
Exercise
You declare public interface Notifier { void send(String message); } and write public class EmailNotifier implements Notifier { void send(String message) { /* ... */ } }. The compile fails. What is wrong, and how do you fix it?
Show answer
The implementing method has no access modifier, so it has default (private) access. An implementation of an interface method must be public (or global). Change the declaration to public void send(String message).
Exercise
A class ReportJob already extends BaseJob. It also needs to be sortable and to expose a label() method defined by your own Labeled interface. Can it do this, and how?
Show answer
Yes. A class can extend only one parent, but it can implement several interfaces. Declare it as public class ReportJob extends BaseJob implements Comparable, Labeled and supply compareTo(Object) and label().