[SalesForce] Unable to access Superclass’s public member variable from Subclass

I am trying assign value into the Super class member variable which is declared as public, but unable to access that SuperClass variable from Subclass.

It is throwing compiler error, Variable does not exist: super.recordId

SuperClass

public virtual class EmployeeSuperClass
{
    public Id recordId {get;set;}
    
    public virtual PageReference displayEmployee()
    {
        //query to retrieve employee data based on recordId
        return null;
    }
}

Subclass

public class EmployeeCustomController extends EmployeeSuperClass{
    private Id recordId {get;set;}
    public EmployeeCustomController()
    {
        recordId = ApexPages.currentPage().getParameters().get('Id');
    }

    public override PageReference displayEmployee(){
        super.recordId = this.recordId;   //giving error ---> Variable does not exist: super.recordId 
        return super.displayEmployee();
    }
}

Am I missing something?

Best Answer

Yes, you are missing something. The Apex Developer Guide lays it out succinctly (emphasis mine):

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.

When you set recordId = someVariable you are setting it at the SuperClass level. Paste this simple analogous script in Execute Anonymous to demonstrate how extending a class works when manipulating member variables and methods (note that classes are virtual by default in that environment):

class SuperClass
{
    String bar;
    public void foo() { system.debug(bar); }
}
class SubClass extends SuperClass
{
    SubClass() { bar = 'Hello World!'; }
}

new SubClass().foo();

So in your implementation, you can actually drop the override entirely. For example, you could implement it as follows:

public virtual class EmployeeSuperClass
{
    Id recordId;
    public PageReference view() {
        return new ApexPages.StandardController(new Employee__c(Id=recordId)).view();
    }
}
public class EmployeeSubClass
{
    public EmployeeSubClass()
    {
        recordId = ApexPages.currentPage().getParameters().get('Id');
    }
}
Related Topic