Salesforce : Apex: How to override class member variables

Varun   Varun 442 Views
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 ? 'NONE' :;

    public void setName(String custName) { = 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;