Note: This release is in preview. Features described here don’t become generally available until the latest general availability date that Salesforce announces for this release. Before then, and where features are noted as beta, pilot, or developer preview, we can’t guarantee general availability within any particular time frame or at all. Make your purchase decisions only on the basis of generally available products and features.

Using the super Keyword

The super keyword can be used by classes that are extended from virtual or abstract classes. By using super, you can override constructors and methods from the parent class.

For example, if you have the following virtual class:
1public virtual class SuperClass {
2    public String mySalutation;
3    public String myFirstName;
4    public String myLastName;
5
6    public SuperClass() {
7
8        mySalutation = 'Mr.';
9        myFirstName = 'Carl';
10        myLastName = 'Vonderburg';
11    }
12
13    public SuperClass(String salutation, String firstName, String lastName) {
14
15        mySalutation = salutation;
16        myFirstName = firstName;
17        myLastName = lastName;
18    }
19
20    public virtual void printName() {
21
22        System.debug('My name is ' + mySalutation + myLastName);
23    }
24
25   public virtual String getFirstName() {
26       return myFirstName;
27   }
28}
You can create the following class that extends Superclass and overrides its printName method:
1public class Subclass extends Superclass {
2  public override void printName() {
3        super.printName();
4        System.debug('But you can call me ' + super.getFirstName());
5    }
6}

The expected output when calling Subclass.printName is My name is Mr. Vonderburg. But you can call me Carl.

You can also use super to call constructors. Add the following constructor to SubClass:
1public Subclass() {
2    super('Madam', 'Brenda', 'Clapentrap');
3}

Now, the expected output of Subclass.printName is My name is Madam Clapentrap. But you can call me Brenda.

Best Practices for Using the super Keyword

  • Only classes that are extending from virtual or abstract classes can use super.
  • You can only use super in methods that are designated with the override keyword.