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

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

    It's an operator that returns true if the left side of the expression is an instance of the class name on the right side.

    Think about it this way. Say all the houses on your block were built from the same blueprints. Ten houses (objects), one set of blueprints (class definition).

    instanceof is a useful tool when you've got a collection of objects and you're not sure what they are. Let's say you've got a collection of controls on a form. You want to read the checked state of whatever checkboxes are there, but you can't ask a plain old object for its checked state. Instead, you'd see if each object is a checkbox, and if it is, cast it to a checkbox and check its properties.

    if (obj instanceof Checkbox)
    {
        Checkbox cb = (Checkbox)obj;
        boolean state = cb.getState();
    }
    

提交回复
热议问题