Given this class:
abstract class Foo{
public Foo(){...}
public abstract void checkable();
public void calledWhenCheckableIsCalled(){
System.out.println("checkable was called");
}
}
Is there any code I can put in Foo's constructor to make calledWhenCheckableIsCalled
get called when checkable
is called?
Note: This is a gross simplification of an actual project I am working on.
Edit: I have already implemented a template pattern workaround. I just wondered if there was another way to do this I am missing. (Perhaps using reflection.)
Looks like a template method pattern.
But then you must implement
Foo.checkable()
and introduce another abstract method to delegate to.I would also suggest to make
checkable()
final in this case so that you can be sure thatcheckable()
can not implemented in another way as you expected.In addition to Brian Roach's comment
That's true, but you can prevent a
Foo
instance from being instantiated if a subclass increases the visibility ofdoCheckable
. Therefore you have to introduce a verification whenever an object is instantiated. I would recommend to use an initializer code so that the verification is executed on every constructor that exists. Then it can not be forgotten to invoke and therefore be by-passed.For example:
Since the check is implemented using reflection the downside is that it is only checked at runtime. So you will not have compiler support of course. But this approach let you enforce that an instance of a
Foo
can only exist if it fulfills your contract.