Sub topic 3
Extending Classes with `virtual`, `abstract`, and `override`
Assume you know Apex variables, collections, transactions, and basic objects and methods. This chapter focuses on choosing between inheritance, interfaces, and other class constructs.
Extending classes
An Apex class must be declared virtual or abstract before another class can extend it. A virtual method has a default implementation that a child class may replace. An abstract class can require child classes to implement methods. The child uses override to replace an inherited method, and super to call the parent implementation.
public abstract class Shape {
public abstract Decimal area();
public virtual String describe() {
return 'Area: ' + area();
}
}
public class Rectangle extends Shape {
private Decimal width;
private Decimal height;
public Rectangle(Decimal width, Decimal height) {
this.width = width;
this.height = height;
}
public override Decimal area() {
return width * height;
}
public override String describe() {
return 'Rectangle, ' + super.describe();
}
}Polymorphism and interfaces
Polymorphism lets one variable hold different implementations. Program against an interface when callers need a capability, not a particular class.
public interface Discount {
Decimal apply(Decimal amount);
}
public class PercentDiscount implements Discount {
private Decimal percent;
public PercentDiscount(Decimal percent) {
this.percent = percent;
}
public Decimal apply(Decimal amount) {
return amount - amount * percent / 100;
}
}
Discount discount = new PercentDiscount(10);
System.debug(discount.apply(100)); // 90System interfaces: `Comparable`
Implement Comparable when a custom object must work with List.sort(). Return a negative value, zero, or a positive value when the current object belongs before, equal to, or after the other object.
public class Employee implements Comparable {
public Decimal salary;
public Employee(Decimal salary) {
this.salary = salary;
}
public Integer compareTo(Object value) {
Employee other = (Employee)value;
return salary == other.salary ? 0 : (salary < other.salary ? -1 : 1);
}
}Inner classes and sharing
An inner class is declared inside another class. Apex inner classes are implicitly static, so create one with Outer.Inner. Keep them focused because they are tied to the outer class's namespace and can make large classes harder to navigate.
with sharing respects record-sharing rules. without sharing ignores them for the class's database operations. inherited sharing follows the caller's sharing mode. Sharing keywords do not replace object- or field-level security checks.
Exercise
Exercise
Which construct is best for a method that needs each object's own state?
Show answer
An instance method, because it can read and update that object's instance variables.