Here’s the scenario -> imagine there are 3 classes, i want to do something kind of like:
public class GameObject {
public void updateBounds() {
// do something
}
}
public abstract class Enemy extends GameObject {
public abstract void updatePosition(){ //<-- this will not compile,
//but this is what i want to do, to force
//child to override parent method
updateBounds();
}
}
public class Minion extends Enemy {
@Override
public void updatePosition() {
super.updatePosition(); // <-- how do i throw an exception if this line
// is not called within this method of the
// child?
// now do something extra that only Minion knows how to do
}
}
- how do you design the Enemy class so that it has a method which does something, but requires every child to override it?
- how do you force the child (who had to override the method) to also call the parent’s method?
this is almost like Android’s Activity class that has the onCreate, onStart, onResume…etc. methods that are optional, but if you make use of it, it forces you to call super. it can’t be abstract because i want some code to be run when the method is called (which is only in the parent class’s method). bonus points if u know how they did it this way?
The Android Sources use a boolean called
mCalledthat is set to true inside of the quasi-abstract method implementation. In your case that would be inside of the originalupdatePosition().Then when you want to call
updatePosition(), call it through this:and
updatePosition()would look like thisEDIT:
Now that I think about it, the way android does it is a little round about. Because all calls to
updatePosition()are going throughperformUpdatePosition(), you no longer need to have some code insideupdatePosition()that can be overridden, but shouldn’t.A much better approach is to simply move the required actions to
performUpdatePosition():This way the callee doesn’t have to worry about calling
super.updatePosition. If the subclass doesn’t override that function, then nothing extra will happen, whereas if they do, the override will add on to the previous behavior.