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

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

    Can be used as a shorthand in equality check.

    So this code

    if(ob != null && this.getClass() == ob.getClass) {
    }
    

    can be written as

    if(ob instanceOf ClassA) {
    }
     
    

提交回复
热议问题