Originally I had a design problem where I needed five subclasses of a superclass, where all but two would use the same generic method of doing things and the other two classes would need special handling. I wanted to avoid writing the method five times; two special cases and three identical ones.
So I had every class inherit SuperClass, and its doSomething() method, and had SubClassSpecial1 and SubClassSpecial2 override with their own doSomeThing method.
This was all fine until I wrote a method which looked something like
void fooBar(SuperClass obj) {
obj.doSomething()
}
and it could be called as fooBar( new SubClassSpecial1() );
The problem is that the runtime class of the obj
variable is now that of its superclass, and thus it will call the methods defined in the superclass. I could, of course, make an abstract doSometing() method in the superclass, and make each subclass implement its own version, but that would duplicate code in three of the classes. And I want to avoid doing that ...
I would lose any gain polymorphism gives if I had a lot of branching through
if(obj.getClass().getName() == "SubClassSpecial1" ) ((SubClassSpecial1) obj).doSomething()K;
else if ...
So what should I do in order to make the design more elegant and un-hackish?