Is there a way to avoid type-checking in this scenario?

Posted by Prog on Programmers See other posts from Programmers or by Prog
Published on 2014-08-18T17:35:03Z Indexed on 2014/08/18 22:31 UTC
Read the original article Hit count: 247

I have a class SuperClass with two subclasses SubClassA and SubClassB. I have a method in a different class which takes a SuperClass parameter.

The method should do different things depending on the type of the object it receives. To illustrate:

public void doStuff(SuperClass object){
    // if the object is of type SubClassA, do something.
    // if it's of type SubClassB, do something else.
}

I want to avoid type-checking (i.e. instanceof) because it doesn't feel like proper OO design.

But I can't figure out how to employ Polymorphism to elegantly solve this problem.

How can I solve this problem elegantly?

© Programmers or respective owner

Related posts about object-oriented

Related posts about polymorphism