4

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.

3
  • Are you able to modify the old class or are you stuck with it as written?
    – Adrian Larson
    Dec 7 '17 at 19:02
  • I can change either class as long as the API remains the same.
    – zeneto
    Dec 7 '17 at 19:05
  • For example, users used to call System.debug(testParentInstance.myName); and will now be able to call System.debug(testChildInstance.myName); in a similar way. I can't just replace it with a testChildInstance.getMyName() for example.
    – zeneto
    Dec 7 '17 at 19:07
3

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.';
    }
}
2
  • Interesting. So I just need a protected property and default virtual getter+setter for each property, and change my subclass to refer to the protected variables instead. Wordy, but this should work. Thanks!!
    – zeneto
    Dec 7 '17 at 19:34
  • @zeneto glad I could help!
    – sfdcfox
    Dec 7 '17 at 20:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.