Java instanceof Keyword
Understanding the Java instanceof Keyword
In Java, the instanceof keyword is used to check whether an object is an instance of a specific class, subclass, or interface. It returns true if the object is an instance of the specified type, otherwise it returns false. This keyword is particularly useful in scenarios where you need to perform type checks or downcast objects safely.
syntax of the instanceof operator:
object instanceof type
Here, object is the instance to be checked, and type is the class, subclass, or interface being checked against.
Usage:
The instanceof operator is commonly used in scenarios such as:
- Type Checking: To verify if an object belongs to a certain class or interface before casting.
- Polymorphism: To determine the actual runtime type of an object in polymorphic scenarios.
- Handling Interfaces: Checking if an object implements a particular interface.
- Avoiding Class Cast Exceptions: Ensuring safe downcasting by first checking the object's type.
Example 1: Type Checking
Object obj = new String("Hello");
if (obj instanceof String) {
String str = (String) obj;
System.out.println("Length of string: " + str.length());
}
In this example, we first check if obj is an instance of String before casting it to String type to safely access the length() method.
Example 2: Polymorphism
class Animal { }
class Dog extends Animal { }
public class Main {
public static void main(String[] args) {
Animal dog = new Dog();
if (dog instanceof Dog) {
Dog myDog = (Dog) dog;
myDog.bark();
}
}
}
Here, instanceof helps ensure that dog is indeed an instance of Dog before downcasting it to Dog type to call bark() method.
Example 3: Interface Checking
interface Shape { }
class Circle implements Shape { }
public class Main {
public static void main(String[] args) {
Shape shape = new Circle();
if (shape instanceof Circle) {
Circle circle = (Circle) shape;
circle.draw();
}
}
}
In this case, we use instanceof to check if shape implements the Circle interface before casting it to Circle type to invoke draw() method.