Atom Feed SITE FEED   ADD TO GOOGLE READER

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.
Doesn't that mean that the class is no longer the "base" implementation and that instead you should be, yourself, extending it to add the new functionality?
If the type Sub isn't referenced directly within the application, you could of course have a wrapper that extends Base and contains an instance of Sub within. Alternatively, if creation of Sub's instances is under you control (created through a factory for example), you could further override prepareForMission in Sub's subclass and return instances of that class everywhere. The latter approach is, of course, valid only if loadUpSecretPlans is visible within Sub's subclass, and can be called after calling loadUpInfantry, loadUpWeapons and loadUpOxygen get invoked.
Am I missing some detail here?
Josh, your solution is simple and standard, and it's definitely what you should do in a situation like this.
Guess that's why you said "don't do this" :)
It's not as ugly as getting the stack call and changing the behavior depending on "who's calling?".
That's a code insanity I'm always crazy about ;-)