Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 36 ยท Classes and Testing

Apex Inheritance, Virtual Methods and Abstract Classes

Learn Apex inheritance: virtual and abstract classes, override, super, polymorphism and when to prefer composition, with real Apex and runnable Java stand-ins.

Inheritance lets one class build on another. In Apex it is the engine behind trigger handler base classes, shared batch logic and exception hierarchies. But Apex is stricter than Java here: a class cannot be extended, and a method cannot be overridden, unless you opt in with virtual or abstract. This lesson shows the keywords, the polymorphism they enable, and the limits of the technique. It builds on classes and interfaces.

Apex cannot run on this site. Apex listings are read-only; the runnable examples are Java stand-ins that model the same inheritance rules. Differences are called out in the text.

virtual: opening a class for extension

By default an Apex class is final. Mark it virtual to allow subclasses, and mark individual methods virtual to allow overrides:

APEX
public virtual class Notifier {
    public virtual String format(String message) {
        return 'Info: ' + message;
    }

    public void send(String message) {
        System.debug(format(message));
    }
}

public class UrgentNotifier extends Notifier {
    public override String format(String message) {
        return 'URGENT: ' + message.toUpperCase();
    }
}

Two things to notice. The subclass uses extends, and the overriding method must say override. The method send is not virtual, so subclasses cannot change it, but it calls format, which does the subclass's work. That is polymorphism: the code in send does not know which format will run.

APEX
Notifier n = new UrgentNotifier();
n.send('disk almost full'); // debug log: URGENT: DISK ALMOST FULL

abstract: classes that must be extended

An abstract class cannot be instantiated and may declare abstract methods with no body. Each concrete subclass must implement them.

APEX
public abstract class ReportBase {
    public abstract List<String> loadRows();

    public String render() {
        return String.join(loadRows(), '\n');
    }
}

public class TopAccountsReport extends ReportBase {
    public override List<String> loadRows() {
        List<String> rows = new List<String>();
        for (Account a : [SELECT Name FROM Account ORDER BY AnnualRevenue DESC NULLS LAST LIMIT 3]) {
            rows.add(a.Name);
        }
        return rows;
    }
}

This is the template method pattern: render fixes the steps, subclasses supply the varying part.

super and constructors

Inside a subclass, super.method() calls the parent's version and super(args) calls a parent constructor. If the parent has only constructors with parameters, the subclass constructor must call super(...) first.

APEX
public virtual class Greeter {
    protected String name;
    public Greeter(String name) { this.name = name; }
    public virtual String hello() { return 'Hello, ' + name; }
}

public class LoudGreeter extends Greeter {
    public LoudGreeter(String name) { super(name); }
    public override String hello() { return super.hello() + '!!!'; }
}

Exception hierarchies

Custom exceptions are the most common inheritance in Apex. Any class whose name ends in Exception and that extends Exception is an exception type; the platform gives you the constructors.

APEX
public class OrderException extends Exception { }
public class PaymentDeclinedException extends OrderException { }

try {
    throw new PaymentDeclinedException('Card declined');
} catch (OrderException e) {
    System.debug('Caught: ' + e.getMessage()); // Caught: Card declined
}

Catching the parent type catches every subclass, as in Java.

Try the idea: template method (Java stand-in)

Java Stand-in: abstract base class with a template method (Java)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

In Java the @Override annotation is optional and methods are virtual by default. In Apex the virtual/override words are required, which makes accidental overrides impossible.

Try the idea: super and exception hierarchy (Java stand-in)

Java Stand-in: super calls and catching a parent exception (Java)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Composition over inheritance

Inheritance couples a child to its parent forever, and Apex allows only single inheritance (one extends), although a class can implement many interfaces. When behaviour varies independently, hold a collaborator behind an interface instead of extending a class. A trigger handler that receives a Validator and a Notifier is easier to test than one that inherits from a giant base class. A good rule: inherit when the relationship is "is a" and the base class is small and stable; compose otherwise.

classDiagram
    class ReportBase {
        <<abstract>>
        +loadRows() List
        +render() String
    }
    ReportBase <|-- TopAccountsReport
    ReportBase <|-- OverdueInvoicesReport

One abstract parent defines the steps; each report fills in how rows are loaded.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What must you add to a method so that a subclass can change its behaviour in Apex?

    Apex methods are not overridable unless declared virtual or abstract, and the subclass must then use override.
  2. 2. What happens if you write new ReportBase() for an abstract class?

    Abstract classes are incomplete by design; you instantiate a concrete subclass.
  3. 3. How many classes can an Apex class extend?

    Apex has single inheritance for classes, but a class can implement several interfaces.
  4. 4. In the template method pattern, which part does a subclass supply?

    The base class fixes the algorithm; the subclass implements the abstract step.

Summary

  • Apex classes are final unless virtual or abstract; overriding methods use override.
  • super reaches the parent's method or constructor.
  • Custom exceptions extend Exception; catch the parent to catch the family.
  • Single inheritance only; use interfaces and composition for flexibility.

Next: Apex Test Classes and Assertions