How to call overridden methods in a subclass? Potential Refactoring Candidate

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?

+5
source share
3 answers

What you described should work fine as it is.

obj.doSomething() ? , . , .

+2

:

, , doSomething(), , obj . .

, , doSomething() .

, , , , , . foobar:

SuperClass sc1 = new SubClassSpecial1();
SubClassSpecial2 sc2 = new SubClassSpecial2();
//etc..
+5

:

void fooBar(SuperClass obj) {
    obj.doSomething();
}

<< → obj SuperClass. , , SuperClass doSomething().
SuperClass, . foobar() , obj, , SuperClass doSomething().

:

fooBar( new SubClassSpecial1() );

, runtime SubClassSpecial1, doSomething(). .

A word about refactoring. You may consider reorganizing your hierarchy.
Your base class SuperClassshould define doSomething()as abstract. Three classes that need the same implementation doSomething()must inherit it from an intermediate base class that has this particular implementation. Your two special classes must inherit directly from SuperClassand have their own implementation doSomething().

+1
source