What is the 'instanceof' operator used for in Java?

前端 未结 17 882
梦毁少年i
梦毁少年i 2020-11-22 03:03

What is the instanceof operator used for? I\'ve seen stuff like

if (source instanceof Button) {
    //...
} else {
    //...
}

17条回答
  •  醉话见心
    2020-11-22 03:55

    As described on this site:

    The instanceof operator can be used to test if an object is of a specific type...

    if (objectReference instanceof type)
    

    A quick example:

    String s = "Hello World!"
    return s instanceof String;
    //result --> true
    

    However, applying instanceof on a null reference variable/expression returns false.

    String s = null;
    return s instanceof String;
    //result --> false
    

    Since a subclass is a 'type' of its superclass, you can use the instanceof to verify this...

    class Parent {
        public Parent() {}
    }
    
    class Child extends Parent {
        public Child() {
            super();
        }
    }
    
    public class Main {
        public static void main(String[] args) {
            Child child = new Child();
            System.out.println( child instanceof Parent );
        }
    }
    //result --> true
    

    I hope this helps!

提交回复
热议问题