History:
The instanceof keyword was introduced in Java to check if an object belongs to a specified type or its subtype. The mechanism allows for runtime type verification, which is important for working with generics, polymorphism, and type casting.
Problem:
Without proper type checking, ClassCastException errors or incorrect logic processing can occur in code branches if type casting is done without checking. Excessive use of instanceof is often a sign of poor design.
Solution:
instanceof returns true if the object is an instance of the specified class or any of its subclasses, or implements the interface. In Java 16, a pattern matching was introduced with automatic type casting in the if block.
Code example:
Object obj = "Hello!"; if (obj instanceof String) { String s = (String) obj; // Safe cast System.out.println(s.length()); }
With Java 16:
if (obj instanceof String s) { System.out.println(s.length()); // s is automatically cast to String }
Key features:
null instanceof Type always false)What does null instanceof SomeClass return?
Always false. The operator guarantees that if the object is null, the result is false, avoiding NullPointerException.
Can you use instanceof with generic parameters, e.g., if (obj instanceof List<String>)?
No. Due to type erasure, you can't check generic parameters at runtime. The check is always made only on the raw type (e.g., List).
Code example:
List<String> list = ...; if (list instanceof List<String>) { ... } // Compilation error if (list instanceof List) { ... } // Allowed
Can the use of instanceof indicate design problems in code?
Yes. Constant use of instanceof instead of applying abstractions or patterns (e.g., the Visitor pattern) often indicates a violation of OOP principles such as open/closed principle.
The method contains a large chain of if-else checking all possible subclasses of one superclass through instanceof, where each branch contains type casting and calls the corresponding method.
Pros:
Cons:
Instead of if-else, the Visitor pattern is implemented: each subclass has a method that calls the required behavior, eliminating the need for instanceof.
Pros:
Cons: