I have a class Child that extends Parent.
Parent child = new Child();
if (child instanceof Parent){
// Do something
}
<
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 ReferenceType15.20.2. Type Comparison Operator instanceof
...
At run time, the result of theinstanceofoperator istrueif the value of the RelationalExpression is notnulland the reference could be cast to the ReferenceType without raising aClassCastException. Otherwise the result isfalse.