Sub topic 11
Extending Classes with virtual, abstract, and override
This chapter covers how one Apex class extends another. It assumes you can declare classes, use access modifiers, write constructors, and tell instance members from static ones. It also assumes you have seen interfaces. Here the focus is inheritance: the keywords that allow it, the rules that govern it, and the mistakes that most often trip people up.
Why Apex needs explicit permission to extend
In many languages any non-final class can be subclassed. Apex works the other way around. A class cannot be extended unless its author opts in with virtual or abstract. Methods follow the same rule. A method cannot be overridden unless it is declared virtual, abstract, or is itself an override.
This default protects code that you did not design for extension. A subclass depends on the internals of its parent. If the parent was never meant to be extended, changing it later could break classes you cannot see.
| Keyword | Applies to | Meaning |
|---|---|---|
| `virtual` | class, method, property | May be extended or overridden. A virtual method has a body. |
| `abstract` | class, method | A class marked abstract cannot be instantiated. An abstract method has no body and must be implemented by a concrete subclass. |
| `override` | method, property | Marks a subclass member that replaces a virtual or abstract member of the parent. |
| `extends` | class declaration | Names the single parent class. |
| `super` | inside a subclass | Refers to the parent class: calls its methods or constructors. |
A virtual class
A virtual class is a normal class that allows subclasses. It can be instantiated on its own.
public virtual class Notifier {
protected String channel;
public Notifier() {
this('email');
}
public Notifier(String channel) {
this.channel = channel;
}
public virtual String format(String message) {
return '[' + channel + '] ' + message;
}
public String send(String message) {
return format(message);
}
}Three details matter here.
formatisvirtual, so subclasses may replace it.sendis not virtual. No subclass can change it. It still callsformat, so the subclass's version offormattakes effect insidesend.channelisprotected. A protected member is visible to the declaring class and to its subclasses, but not to unrelated code. This is the access level you reach for when designing a base class.
A subclass with override and super
public class SmsNotifier extends Notifier {
public SmsNotifier() {
super('sms');
}
public override String format(String message) {
String shortened = message.abbreviate(40);
return super.format(shortened);
}
}
// Usage
Notifier n = new SmsNotifier();
System.debug(n.send('Your order has shipped and will arrive on Friday.'));
// [sms] Your order has shipped and will arrive on...The variable n has the type Notifier, but the object is an SmsNotifier. Apex picks the method from the object's real class at runtime. This is dynamic dispatch, and it is what makes send call the subclass's format.
Inside format, super.format(shortened) runs the parent version. Use it when you want to add behavior around the parent's work, not replace it.
Constructors in a hierarchy
Constructors are not inherited. Each subclass declares its own. A subclass constructor must start by calling a parent constructor with super(...). If you write no explicit call, Apex calls the parent's no-argument constructor for you.
That implicit call causes a common compile error. If the parent has only constructors that take arguments, the subclass must call one explicitly.
public virtual class Account2 {
public Account2(String name) { }
}
public class Customer extends Account2 {
// Compile error without this constructor:
// there is no no-argument constructor in Account2 to call implicitly.
public Customer() {
super('Unnamed');
}
}Constructors run from the top of the hierarchy down. The parent constructor finishes before the subclass constructor body starts.
Abstract classes
An abstract class is incomplete on purpose. It defines the shared parts of a design and leaves some methods for subclasses to supply. You cannot write new on an abstract class.
public abstract class Report {
public abstract String title();
public abstract List<String> rows();
public String render() {
List<String> lines = new List<String>{ title() };
lines.addAll(rows());
return String.join(lines, '\n');
}
}
public class OpenCasesReport extends Report {
public override String title() {
return 'Open cases';
}
public override List<String> rows() {
List<String> result = new List<String>();
for (Case c : [SELECT Subject FROM Case WHERE IsClosed = false LIMIT 5]) {
result.add(c.Subject);
}
return result;
}
}render is a template method. The base class fixes the order of steps, and subclasses fill in the parts that vary. A concrete subclass that skips an abstract method fails to compile.
An abstract class may mix abstract methods with ordinary ones, hold fields, and declare constructors. An interface cannot hold fields or constructors, so this is the main practical difference between the two.
Rules for overriding
- The overriding method needs the
overridekeyword. Leaving it out is a compile error. - The signature must match the parent's: same name and parameter types.
- The return type must match. Apex does not support covariant return types in the way some languages do, so do not assume a narrower return type is allowed.
- The overriding method cannot be less visible than the parent's. A
public virtualmethod cannot becomeprivatein a subclass. - Only one parent class is allowed. A class may extend one class and implement many interfaces.
public class Priority extends Notifier implements Comparable {
public Integer compareTo(Object other) {
return 0;
}
}Overriding is not hiding
Static methods cannot be overridden. A static method belongs to the class, so there is no object whose real type could pick a version. Fields work the same way. Declaring a field with the same name in a subclass does not replace the parent's field. It creates a second, separate one. Because of this, keep shared state in the base class and change behavior through methods.
Calling the parent from the parent's own code
A virtual method that calls another virtual method on this is the usual source of surprises. In Notifier, send calls format. If a subclass overrides format and also calls super.send(...) from somewhere, the call comes back to the subclass's format. Document which methods a base class calls internally, because a subclass author has to know that.
Type checks and casts
When you hold a parent-typed variable, you can test the real type with instanceof and convert with a cast.
Notifier n = new SmsNotifier();
if (n instanceof SmsNotifier) {
SmsNotifier sms = (SmsNotifier) n;
System.debug('Is SMS');
}A cast to the wrong class throws a System.TypeException at runtime. Check first, or better, put the behavior in an overridden method so the cast is not needed.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| "Class cannot be extended" | Parent is not `virtual` or `abstract` | Add `virtual` to the parent, if extension is intended. |
| "Overriding method must use the override keyword" | `override` missing | Add `override`. |
| "Method does not override an inherited method" | Name, parameters, or return type differ, or the parent method is not virtual | Match the parent signature exactly. |
| "Class must implement the abstract method" | Concrete subclass skipped an abstract method | Implement every abstract method. |
| "No default constructor available" | Parent has only argument constructors | Call `super(...)` explicitly. |
| `System.TypeException` | Invalid cast at runtime | Test with `instanceof`, or use polymorphism. |
The exact wording of compiler messages can differ between releases, but the causes are the same.
Inheritance or interface?
Choose an abstract or virtual class when subclasses share real code or state and are closely related. Choose an interface when unrelated classes only need to agree on a contract. Inheritance couples a subclass tightly to its parent, and a class has only one parent. Interfaces carry no such cost, so prefer them unless you need to share implementation.
Exercise
A class Base declares public virtual String name(). A subclass declares public String name() with the same body logic but no extra keyword. What happens, and what is the fix?
Show answer
The subclass fails to compile because a method that replaces a virtual method must be marked override. Change the subclass method to public override String name().
Exercise
You write Report r = new Report(); where Report is an abstract class. Why does it fail, and how do you get a usable object?
Show answer
An abstract class cannot be instantiated. Create a concrete subclass that implements every abstract method, then instantiate that, for example Report r = new OpenCasesReport();.