Search code examples
javainheritancesubclasssuperclassinformation-hiding

What's the default behaviour of subclass method without using super?


Is there a possibility to have some default behaviour defined for a method in a subclass, without having to call super?

E.g: Suppose we want to set a boolean value in the superclass and you want to hide this from the subclass, is there a way to hide the modification of the boolean value? Suppose that we have the following base class BaseTest

public class BaseTest {
    private boolean mIsInitialized = false;

    public BaseTest() {
    }

    public void initialize() {
        mIsInitialized = true;
    }
}

and its subclass Test:

public class Test extends BaseTest {
    public Test() {
    }

    public void initialize() {
    }
}

I would like for the call to Test.initialize() to set the mIsInitialized value to true without having to call super.initialize(). I would equally like to avoid to define an abstract function in the superclass. Is this even possible?


Solution

  • @rgettman et al. are calling for using the Template pattern. Therein you make explicit the fact that subclasses may "hook in" to the superclass's action through specific overridable methods that are not initialize, which seems to go against the spirit of your question.

    You can also use an aspect-oriented framework like AspectJ to have all kinds of invisible behaviors attached to method calls.