Salesforce : Apex: How to override class member variables

You can' t override class members directly and if you try to define them  virtual/abstract to override in extending class then you get following compile time error:

Compile Error: Variables cannot be marked as virtual

Use setter and getter technique to override member variables, following is the example,


public virtual class MyRecord {
    public String name;

    public virtual String getName() {
        return this.name==null ? 'NONE' : this.name;
    }

    public void setName(String custName) {
        this.name = name;
    }
}

public class MyRecordsExtended extends MyRecord {
    private Set<String> myRecords;

    public override String getName() {
        String csvNames = '';
        for(String rec : myRecords){
            csvNames = csvNames+','+ rec;
        }

        return csvNames; 
    }
}


Comments

Popular Posts