[SalesForce] Overriding Getters and Setters from Base Class

I'm trying to convert an old global class to be a virtual class so I can have some variations on its implementation. There is some existing behavior on the property Getters that I'd like to preserve in one of my new concrete subclasses.

The parent looks something like this:

global virtual class TestParent {
    global String myName {get;set;}
    global virtual void sayHi() { }
}

And the subclass looks like this.

global class TestChild extends TestParent {
    global String getMyName() {
       return myName + ' Smith';
    }
    global override void sayHi() {
        System.debug('Hello, ' + myName );
    }    
}

What I'd like to do is be able to override the {get;} defined on my parent class in the subclass to perform some logic against the accessed attribute.

My thinking above was that global String myName {get;set;} would translate to a getMyName() method, but the property can't override it that way. Because the parent call is released as global, I need to continue being able to access the Child class the same way I used to access the Parent class, so I can't change it's implementation unless it continues exposing the same outward API.

Any help appreciated.

Best Answer

You can do this, but it's not straight-forward. You need to set up the parent and child as follows:

global virtual class TestParent {
    protected virtual String getName() {
        return protectedName;
    }
    protected String protectedName;
    public String myName { get { return getName(); } set { protectedName = value; } }
}
global class TestChild extends TestParent {
    protected override String getName() {
        return 'Hello there.';
    }
}
Related Topic