I'm going through Java For Everyone by Cay Horstmann.
I'm a bit confused on when it says:
Don't Use Type Tests
This is about using instanceof
operator for specific type tests in order to implement behavior that varies with each class like (taken straight from the book):
if (q instanceof ChoiceQuestions) //Don't do this
{
//Do the task the ChoiceQuestion way
}
else if (q instanceof Question)
{
//Do the task Question way
}
Apparently this is a poor way to do it as if you have a new class like NumericQuestion
added you need to revise all parts of your program that make a type test, adding another case.
It is better to add class NumericQuestion
to the program. Nothing needs to change as we are using polymorphism, not type tests.
When ever you find yourself trying to use tyepe tests in a hierarchy of classes, reconsider and use polymorphism instead. Declare a method doTheTask
in the superclass, override it in the subclasses and call q.doTheTask()
What I don't understand is the last paragraph, the one above. Can someone shoe me an example of what it means please? (I'm kind of a visual learner). How do we actually do this without using tyep tests?