top of page
shubhangisingh453

Understanding Java's instanceof Operator : A Comprehensive Guide



📗 Definition

Java's instanceof operator is a binary operator used to test whether an object belongs to a specific class or interface. It returns a boolean value that indicates whether the object is an instance of the specified class or a subclass of it, or an instance of a class that implements the specified interface.


The general syntax of instanceof operator is:


object instanceof class

Here, object is the object whose type is being tested, and class is the class or interface being tested against.

Let's look at some examples to understand how instanceof works:


♦ Example 1: Testing if an object is an instance of a class



class Animal {
    // class implementation
}

class Dog extends Animal {
    // class implementation
}

Animal animal = new Animal();
Dog dog = new Dog();

boolean isAnimal = animal instanceof Animal; // true
boolean isDog = animal instanceof Dog; // false

isAnimal = dog instanceof Animal; // true
isDog = dog instanceof Dog; // true

In this example, we have two classes Animal and Dog. Dog is a subclass of Animal. We create two objects animal and dog of these classes. We use the instanceof operator to test whether these objects are instances of Animal or Dog classes.

The first instanceof expression animal instanceof Animal returns true because animal is an instance of the Animal class. The second instanceof expression animal instanceof Dog returns false because animal is not an instance of the Dog class.

The third instanceof expression dog instanceof Animal returns true because dog is an instance of both Animal and Dog classes. The fourth instanceof expression dog instanceof Dog returns true because dog is an instance of the Dog class.


♦ Example 2: Testing if an object implements an interface



interface Drawable {
    void draw();
}

class Circle implements Drawable {
    // class implementation
}

class Square {
    // class implementation
}

Drawable drawable = new Circle();
Square square = new Square();

boolean isDrawable = drawable instanceof Drawable; // true
boolean isSquareDrawable = square instanceof Drawable; // false

In this example, we have an interface Drawable and two classes Circle and Square. The Circle class implements the Drawable interface. We create two objects drawable and square of these classes. We use the instanceof operator to test whether these objects implement the Drawable interface.

The first instanceof expression drawable instanceof Drawable returns true because drawable is an instance of the Circle class which implements the Drawable interface. The second instanceof expression square instanceof Drawable returns false because square is not an instance of any class that implements the Drawable interface.


♦ Example 3: Testing if an object is an instance of a superclass



class A {
    // class implementation
}

class B extends A {
    // class implementation
}

class C extends B {
    // class implementation
}

A a = new A();
B b = new B();
C c = new C();

boolean isA = a instanceof A; // true
boolean isB = b instanceof A; // true
boolean isC = c instanceof A; // true

In this example, we have three classes A, B, and C. B is a subclass of A, and C is a subclass of B. We create three objects a, b, and c of these classes. We use the instanceof operator to test whether these objects are instances of the A class.

The first instanceof expression a instanceof A returns true because a is an instance of the A class. The second instanceof expression b instanceof A returns true because b is an instance of the B class, which is a subclass of A. The third instanceof expression c instanceof A returns true because c is an instance of the C class, which is a subclass of B, which in turn is a subclass of A.


♦ Example 4: Checking null reference



String str = null;
boolean isString = (str instanceof String); // false

In this example, we have a null reference to a String object. When we use the instanceof operator on a null reference, it returns false.


♦ Example 5: Using instanceof with interfaces



interface Vehicle {
    void move();
}

class Car implements Vehicle {
    // class implementation
}

class Bicycle implements Vehicle {
    // class implementation
}

Vehicle[] vehicles = new Vehicle[] { new Car(), new Bicycle() };

for (Vehicle vehicle : vehicles) {
    if (vehicle instanceof Car) {
        System.out.println("Vehicle is a car");
    } else if (vehicle instanceof Bicycle) {
        System.out.println("Vehicle is a bicycle");
    }
}

In this example, we have an interface Vehicle and two classes Car and Bicycle that implement it. We create an array of Vehicle objects that contains instances of both classes. We use the instanceof operator to test whether each object in the array is an instance of Car or Bicycle. We then print a message indicating the type of the vehicle.

The output of the program is:


Vehicle is a car
Vehicle is a bicycle

In conclusion, the instanceof operator is a useful tool for testing the type of an object in Java. It can be used to test whether an object belongs to a specific class or interface, and it can also be used to check whether an object is an instance of a superclass or a subclass. It is important to use the instanceof operator carefully and only when necessary, as overuse can lead to code that is difficult to read and maintain.


The instanceof operator in Java can be used with interfaces and inheritance to check whether an object belongs to a specific class or interface, or whether it is an instance of a superclass or a subclass. Let's take a closer look at how instanceof works in these scenarios.


⚡ Using instanceof with interfaces


In Java, an interface is a collection of abstract methods that can be implemented by any class. When a class implements an interface, it agrees to provide an implementation for all of the methods defined in the interface. The instanceof operator can be used to check whether an object is an instance of a class that implements a specific interface.

Consider the following example:



interface Printable {
    void print();
}

class Document implements Printable {
    public void print() {
        System.out.println("Printing a document...");
    }
}

class Image {
    // class implementation
}

public class Main {
    public static void main(String[] args) {
        Printable p1 = new Document();
        Printable p2 = new Image();

        System.out.println(p1 instanceof Printable); // true
        System.out.println(p2 instanceof Printable); // false
    }
}

In this example, we have an interface Printable with a single abstract method print(). We also have a class Document that implements the Printable interface and provides an implementation for the print() method. We also have a class Image that does not implement the Printable interface.

In the main() method, we create two objects p1 and p2, where p1 is an instance of the Document class and p2 is an instance of the Image class. We use the instanceof operator to check whether each object is an instance of the Printable interface. The first instanceof expression p1 instanceof Printable returns true because p1 is an instance of the Document class, which implements the Printable interface. The second instanceof expression p2 instanceof Printable returns false because p2 is an instance of the Image class, which does not implement the Printable interface.


⚡ Using instanceof with inheritance


In Java, a class can inherit properties and methods from another class. The instanceof operator can be used to check whether an object is an instance of a specific class or any of its superclasses or subclasses.

Consider the following example:


class Animal {
    // class implementation
}

class Mammal extends Animal {
    // class implementation
}

class Dog extends Mammal {
    // class implementation
}

public class Main {
    public static void main(String[] args) {
        Animal a1 = new Animal();
        Mammal m1 = new Mammal();
        Dog d1 = new Dog();

        System.out.println(a1 instanceof Animal); // true
        System.out.println(m1 instanceof Animal); // true
        System.out.println(d1 instanceof Animal); // true

        System.out.println(m1 instanceof Mammal); // true
        System.out.println(d1 instanceof Mammal); // true

        System.out.println(d1 instanceof Dog); // true
        System.out.println(a1 instanceof Mammal); // false
    }
}

In this example, we have a class hierarchy where Animal is the superclass of Mammal, and Mammal is the superclass of Dog. We create three objects a1, m1, and d1 of these classes. We use the instanceof operator to test whether each object is an instance of a specific class or any of its superclasses or subclasses.


Thanks for reading, and happy coding!


Understanding Java's instanceof Operator : A Comprehensive Guide -> Java Inheritance: Understanding Inheritance in Java Programming with Examples

bottom of page