Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should and shouldn't instanceof be used?

Tags:

java

I have gone through various articles, but I still do not know why instanceof should not be used. Kindly let me know your thoughts.

like image 461
Dead Programmer Avatar asked Sep 23 '10 09:09

Dead Programmer


People also ask

When should you not use Instanceof?

The problem with instanceof is that if you have a large amount of Animal s, you'll end up with a long if-else-if for every one of them. It's hard to maintain and prone to errors where e.g. a new type of Animal is added, but you forget to add it to the if-else-if chain.

Should we use Instanceof?

instanceof is a binary operator we use to test if an object is of a given type. The result of the operation is either true or false. It's also known as a type comparison operator because it compares the instance with the type. Before casting an unknown object, the instanceof check should always be used.

What can I use instead of Instanceof?

The isInstance method is equivalent to instanceof operator. The method is used in case of objects are created at runtime using reflection. General practice says if the type is to be checked at runtime then use the isInstance method otherwise instanceof operator can be used.

What is the use of Instanceof operator?

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 .


1 Answers

I find a need to use instanceof hints at bad design. It's a sure sign that a big, complex switch-style construct will follow. Most other times I see it used, we should use polymorphism rather than instanceof. See the Strategy pattern. (relevant examples of use)

The only time I find I need to use it is when implementing equals(Object o).

like image 106
brabster Avatar answered Oct 15 '22 21:10

brabster