Don't do this: evading polymorphism
I've got two classes,Base
and Sub
. I can freely make changes to Base
. But Sub
is written by a third party and I don't have privileges to make changes to it. Here's what they look like:public class Base {
public void prepareForMission() {
loadUpInfantry();
loadUpWeapons();
}
}
public class Sub extends Base {
public void prepareForMission() {
super.prepareForMission();
loadUpOxygen();
}
}
Suppose that I need to change the behaviour for instances of Base
without changing the behaviour of Sub
or other subclasses. The horrible, ugly hack I came up with for this is to evade polymorphism like so:
public class Base {
public void prepareForMission() {
loadUpInfantry();
loadUpWeapons();
if (getClass() == Base.class) {
loadUpSecretPlans();
}
}
}
Doesn't it make ya cringe? I'm quite ashamed of it.