The 'instanceof' operator in Java is a binary operator used to check if an object is an instance of a specific class, superclass, or interface. It returns either true or false after comparing the type of an object with a specified class or interface. Here's an example:
class Vehicle {}
class Car extends Vehicle {}
public class Main {
public static void main(String[] args) {
Car car = new Car();
boolean result = car instanceof Vehicle;
System.out.println(result); // Output: true
}
}
In this example, we created two classes: Vehicle
and Car
. 'Car' is a subclass (or 'child class') of Vehicle
. In the main
method, we created an object of the Car
type, and then used the 'instanceof' operator to determine whether it's an instance of Vehicle
. The result is true
because Car
is indeed a subclass of Vehicle
.
This operator can be particularly useful in object-oriented programming (OOP) where polymorphism is used. Polymorphism allows a child class to inherit the properties and methods of a parent class. Therefore, an object of the child class can be treated as an object of the parent class. The 'instanceof' operator helps determine the actual type of the object at runtime.
class Vehicle {}
class Car extends Vehicle {}
public class Main {
public static void main(String[] args) {
Vehicle myVehicle = new Car();
if (myVehicle instanceof Car) {
System.out.println("myVehicle is an instance of Car");
} else {
System.out.println("myVehicle is NOT an instance of Car");
}
}
}
In this example, myVehicle
is an instance of Car
even though its type is declared as Vehicle
. So, the 'myVehicle instanceof Car' expression is true, thereby it prints "myVehicle is an instance of Car" as output.
It's advisable not to overuse the 'instanceof' operator because it disrupts the clean architecture of an application. It's better to use method overloading and overriding to achieve the same functionality. It's recommended to use 'instanceof' only when necessary, since it creates an unnecessary coupling between classes.