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

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

    Very simple code example:

    If (object1 instanceof Class1) {
       // do something
    } else if (object1 instanceof Class2) {
       // do something different
    }
    

    Be careful here. In the example above, if Class1 is Object, the first comparison will always be true. So, just like with exceptions, hierarchical order matters!

提交回复
热议问题