I have the following :
public Class A { public void methodA() { .... } public void methodB() { .... } }
I don't have control over Class A. I would like to create subclasses of Class A with a restriction that it must override methodA() (super.methodA() call must run the implementation of Class A). is it possible? is so, how?
Best Answer
First thing to understand here is that this part of requirements:
super.methodA()
means this applies to the code of the classes extendingA
, in a way defined in JLS 15.12.4.4-2. Method Invocation Usingsuper
Let's say, we want a way to create some specific subclasses of A such that whenever
super.methodA()
is invoked in these, we are guaranteed that instead of code that was in classA
(out of our control) it will run some other code, defined in some subclass ofA
(under our control).Let's see what "tools" are at our disposal to achieve above.
Need to create some, specific subclasses of
A
brings to mind traditional way to specialize - subclassing, that is we'll consider subclass ofA
(let's call itB
) that would redefine (override)methodA
in the way we want.Need to force a subclass to provide a code that would run where we want it in superclass can be satisfied by defining an abstract method, let's call it
forcedImplementationInSubclass()
Now we've got all what we need.
B
extendingA
, so that all subclasses ofB
will also be subclasses ofA
.B
, we will overridemethodA
, so that its implementation in classA
won't be available to subclasses ofB
anymore.B
we will invoke abstract methodforcedImplementationInSubclass()
which will guarantee that subclasses ofB
will have to define the code that will eventually run inmethodA
.As a result, any subclass of
B
won't be able to invokemethodA
implementation provided in classA
and instead, will be guaranteed to run code defined in some subclass ofB
.Extending
B
is the way to create specific subclasses ofA
that behave as we want. The code could look about as follows: