So I have my base Class X, and Class Y which extends it.
I have a number of methods in class X which are all overridden in class Y,
I would like to put a few statements in one of these methods which get called even when the method is overridden, without having to put any extra code into Class Y.
Is there any way to do this?
public class X
{
protected void method()
{
// vital statements;
}
}
public class Y extends X
{
protected void method()
{
/* vital statements still need to happen
* would rather not have to call it
* in every single class that extends X
*/
// non vital statement;
}
}
The common — and essentially only — way to do this is using the
superkeyword:I say “essentially only” because there are other ways to do this, but they require more change. One technique is to make the central method final and public (so it can be called but not overridden), and have it call a protected abstract method (which can be overridden but not called). Then folks can customize the behavior of a subclass by overriding just the abstract method. This is called the template method pattern.
A third way to accomplish what you want is by using aspects. Using aspect-oriented programming, your “vital statements” could be added to the subclass methods at runtime or compile time, using some behind-the-scenes bytecode magic. This requires some special tooling and adds some complexity to your build system, but it has the advantage of being completely invisible to the authors of the subclasses.