Initially, I had a design problem where I needed five subclasses of the superclass, where all but two would use the same general method of doing things, and the other two classes would need special handling. I would like to avoid writing the method five times; two special cases and three identical.
Thus, each class inherits SuperClass and its doSomething () method and overrides SubClassSpecial1 and SubClassSpecial2 using its own doSomeThing method.
Everything was fine until I wrote a method similar to
void fooBar(SuperClass obj) {
obj.doSomething()
}
and it could be called fooBar( new SubClassSpecial1() );
The problem is that the execution class of the variable is objnow the class of its superclass, and therefore it will call the methods defined in the superclass. I could, of course, make the abstract doSometing () method in the superclass and make each subclass an implementation of its own version, but this will duplicate the code in the three classes. And I want to avoid this ...
I would lose any gain polymorphism if I had many branches through
if(obj.getClass().getName() == "SubClassSpecial1" ) ((SubClassSpecial1) obj).doSomething()K;
else if ...
So what should I do to make the design more elegant and non-hacks?
source
share