How can instanceof be used in Java?

In Java, the instanceof operator can be used to check if an object is an instance of a particular class or one of its subclasses. Here is the syntax for instanceof.

obj instanceof ClassName

obj is the object to be checked and ClassName is the name of the class to be checked.

The instanceof operator returns a boolean value indicating whether obj is an instance of the ClassName class or a subclass of it.

Here is a sample code:

public class Animal {
    // ...
}

public class Dog extends Animal {
    // ...
}

public class Cat extends Animal {
    // ...
}

public class Main {
    public static void main(String[] args) {
        Animal animal = new Animal();
        Dog dog = new Dog();
        Cat cat = new Cat();

        System.out.println(animal instanceof Animal); // true
        System.out.println(dog instanceof Animal); // true
        System.out.println(cat instanceof Animal); // true

        System.out.println(dog instanceof Dog); // true
        System.out.println(cat instanceof Dog); // false

        System.out.println(animal instanceof Dog); // false
        System.out.println(animal instanceof Cat); // false
    }
}

In the above example, animal, dog, and cat are all instances of the Animal class, so the results of animal instanceof Animal, dog instanceof Animal, and cat instanceof Animal are all true.

Since dog is an instance of the Dog class, the result of dog instanceof Dog is true, whereas cat is not an instance of the Dog class, so the result of cat instanceof Dog is false.

Similarly, since an animal is not an instance of the Dog class, the result of “animal instanceof Dog” is false. An animal is also not an instance of the Cat class, so the result of “animal instanceof Cat” is false.

Leave a Reply 0

Your email address will not be published. Required fields are marked *