Does instanceof return true if instance of a parent?

后端 未结 4 1094
孤城傲影
孤城傲影 2020-12-16 09:14

I have a class Child that extends Parent.

Parent child = new Child();

if (child instanceof Parent){
    // Do something
}
<         


        
4条回答
  •  一个人的身影
    2020-12-16 09:48

    Yes. instanceof will be true whenever the reference(left side of the instanceof expression) can be cast to the ReferenceType(the type on the right side of the instanceof expression). This will be true for subclasses in relation to their parent:

    Child child = new Child();
    Parent parent = (Parent) child; //works!
    assert child instanceof Parent; //true
    

    From The Java Language Specification, Java SE 9 Edition:

    15.20. Relational Operators
    ...
    RelationalExpression instanceof ReferenceType

    15.20.2. Type Comparison Operator instanceof
    ...
    At run time, the result of the instanceof operator is true if the value of the RelationalExpression is not null and the reference could be cast to the ReferenceType without raising a ClassCastException. Otherwise the result is false.

提交回复
热议问题