There are two problems with your as-is method. First, suppose you add a new subclass of the Parent class, Child3 . This does not apply to any of your cases, so it does not print anything. The same is true if you add a new subclass of Child1 , ChildOfChild1 . It will also not be covered.
If you used instanceof instead, then ChildOfChild1 will appear as an instance of Child1 , and Child3 will be an instance of Parent .
But, as a rule, the reason you want to completely avoid this pattern is that all these cases may be unexpected. What is generally better to write
void foo(Parent p) {...}
and put the general code there, and then for any special cases, create
void foo(Child1 c) {...}
This makes it clearer what happens: if you see these two methods, you know that Child1 (and its subclasses) has special code, and Parent and all other subclasses are handled in the same way.
source share