Is using the instanceof
keyword against the essence of object oriented programming
?
I mean is it a bad programming practice?
I read somewhere that us
Favor polymorphism and dynamic binding to downcasting and instanceof
. This is the "OO Way" and enables you to write code that doesn't need to know about subtypes.
EXAMPLE
abstract class Animal {
public abstract void talk();
//...
}
class Dog extends Animal {
public void talk() {
System.out.println("Woof!");
}
//...
}
class Cat extends Animal {
public void talk() {
System.out.println("Meow!");
}
//...
}
class Hippopotamus extends Animal {
public void talk() {
System.out.println("Roar!");
}
//...
}
class Main {
public static void main(String[] args) {
makeItTalk(new Cat());
makeItTalk(new Dog());
makeItTalk(new Hippopotamus());
}
public static void makeItTalk(Animal animal) {
animal.talk();
}
}