The `instanceof` operator in Java is used to check whether an object is an instance of a specific class or implements an interface. It returns `true` if the object is an instance of the specified class or interface, and `false` otherwise. This operator is particularly useful for safe typecasting and ensuring that an object can be safely cast to a particular type before performing operations on it.
Syntax:
object instanceof ClassName
Example:
class Animal { }
class Dog extends Animal { }
public class Main {
public static void main(String[] args) {
Animal animal = new Dog();
// Checking if 'animal' is an instance of Dog
if (animal instanceof Dog) {
System.out.println("animal is an instance of Dog");
} else {
System.out.println("animal is NOT an instance of Dog");
}
// Checking if 'animal' is an instance of Animal
if (animal instanceof Animal) {
System.out.println("animal is an instance of Animal");
} else {
System.out.println("animal is NOT an instance of Animal");
}
}
}
Output:
animal is an instance of Dog
animal is an instance of Animal
Explanation:
- In the example above, the `instanceof` operator checks if the `animal` object is an instance of the `Dog` class and the `Animal` class.
- Since `Dog` is a subclass of `Animal`, the `animal` object is both an instance of `Dog` and `Animal`. Therefore, both checks return `true`.
The `instanceof` operator is often used in scenarios where objects might belong to different subclasses, and you want to perform operations specific to a subclass safely.
The instanceof operator returns true if the reference variable being tested is of the type being compared to.