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

前端 未结 17 860
梦毁少年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:51

    The instanceof operator is used to check whether the object is an instance of the specified type. (class or subclass or interface).

    The instanceof is also known as type comparison operator because it compares the instance with type. It returns either true or false.

    class Simple1 {  
    public static void main(String args[]) {  
    Simple1 s=new Simple1();  
    System.out.println(s instanceof Simple1); //true  
    }  
    }  
    

    If we apply the instanceof operator with any variable that has null value, it returns false.

提交回复
热议问题