Site icon

Find type of objects at runtime using instanceof operator (java/ example)

1. Example: find type of object at runtime using instanceof operator in java.

Fig 1: Class hierarchy

2. Program: find type of object using instanceof operator (java/example)

package org.learn;

class Parent {
}

interface Wrestler {
}

interface Model {
}

class Son extends Parent implements Wrestler {
}

class Daughter extends Parent implements Model {
}


public class DemoInstanceOfOperator {

    public static void main(String[] args) {

        Parent parent = new Parent();
        Parent son = new Son();
        Parent daughter = new Daughter();

        //Check instance of operator on parent
        System.out.println("1. parent instanceof Parent: "+ (parent instanceof Parent));
        System.out.println("2. parent instanceof Son: "+ (parent instanceof Son));
        System.out.println("3. parent instanceof Daughter: " + (parent instanceof Daughter));
        System.out.println("4. parent instanceof Wrestler: "+ (parent instanceof Wrestler));
        System.out.println("5. parent instanceof Model: "+ (parent instanceof Model));
        System.out.println();

        //Apply instanceof operator on son
        System.out.println("6. son instanceof Son: "+ (son instanceof Son));
        System.out.println("7. son instanceof Parent: "+ (son instanceof Parent));
        System.out.println("8. son instanceof Object: "+ (son instanceof Object));
        System.out.println("9. son instanceof Wrestler: "+ (son instanceof Wrestler));
        System.out.println("10. son instanceof Model: "+ (son instanceof Model));
        System.out.println();

        //Apply instanceof operator on daughter
        System.out.println("11. daughter instanceof Parent: " + (daughter instanceof Parent));
        System.out.println("12. daughter instanceof Object: " + (daughter instanceof Object));
        System.out.println("13. daughter instanceof Wrestler: " + (daughter instanceof Wrestler));
        System.out.println("14. daughter instanceof Model: "  + (daughter instanceof Model));
    }
}

3. Output: find type of object using instanceof operator (java/example)

1. parent instanceof Parent: true
2. parent instanceof Son: false
3. parent instanceof Daughter: false
4. parent instanceof Wrestler: false
5. parent instanceof Model: false

6. son instanceof Son: true
7. son instanceof Parent: true
8. son instanceof Object: true
9. son instanceof Wrestler: true
10. son instanceof Model: false

11. daughter instanceof Parent: true
12. daughter instanceof Object: true
13. daughter instanceof Wrestler: false
14. daughter instanceof Model: true
Exit mobile version