Is using the instanceof
keyword against the essence of object oriented programming
?
I mean is it a bad programming practice?
I read somewhere that using instanceof
keyword means that the design may not be that good. Any better workaround?
The java “instanceof” operator is used to test whether the object is an instance of the specified type (class or subclass or interface). It is also known as type comparison operator because it compares the instance with type.
The instanceof operator in Java is used to check whether an object is an instance of a particular class or not. objectName instanceOf className; Here, if objectName is an instance of className , the operator returns true . Otherwise, it returns false .
The instanceof keyword is used to check if an object belongs to a class. The comparison returns true if the object is an instance of the class, it returns false if it is not.
Generally speaking yes. It's best to keep all code that depends on being a specific class within that class, and using instanceof
generally means that you've put some code outside that class.
Look at this very simple example:
public class Animal
{
}
public class Dog extends Animal
{
}
public class Cat extends Animal
{
}
public class SomeOtherClass
{
public abstract String speak(Animal a)
{
String word = "";
if (a instanceof Dog)
{
word = "woof";
}
else if (a instanceof Cat)
{
word = "miaow";
}
return word;
}
}
Ideally, we'd like all of the behaviour that's specific to dogs to be contained in the Dog class, rather than spread around our program. We can change that by rewriting our program like this:
public abstract class Animal
{
public String speak();
}
public class Dog extends Animal
{
public String speak()
{
return "woof";
}
}
public class Cat extends Animal
{
public String speak()
{
return "miaow";
}
}
public class SomeOtherClass
{
public String speak(Animal a)
{
return a.speak();
}
}
We've specified that an Animal
has to have a speak
method. Now SomeOtherClass
doesn't need to know the particular details of each type of animal - it can hand that off to the subclass of Animal
.
There are many good answers promoting virtual methods, but instanceof
has its uses as well. Imagine that you iterate over List<Event>
, to pick up all Urgent
objects. You might do it using isUrgent()
but I am not sure if it were necessarily more concise or readable. Also, isUrgent()
would require making Event
aware that its subclasses may possess the respective property, which might:
Event
belongs to some library that can not be modified.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With