JavaRush /Java Blog /Random EN /instanceof operator
articles
Level 15

instanceof operator

Published in the Random EN group
Using the operator instanceof, you can find out which class an object came from. This operator has two arguments. On the left is a reference to the object, and on the right is the name of the type with which the object is checked for compatibility. For example: instanceof operator - 1
Parent р = new Child(); // проверяем переменную р типа Parent
//на совместимость с типом Child print(p instanceof Child);
The result will be true . Thus, the operator instanceofdoes not rely on the type of the reference, but on the properties of the object to which it refers. But this operator returns a true value not only for the type from which the object was derived. Let's add one more to the already declared classes:
// Объявляем новый класс и наследуем
// его от класса Child
class ChildOfChild extends Child {}
Now let's create a variable of a new type:
Parent p = new ChildOfChild();
print(p instanceof Child);
The first line declares a variable of type Parent, which is initialized with a reference to an object derived from ChildOfChild. In the second line, the statement instanceofanalyzes the compatibility of the type reference Parentwith the class Child, and the involved object is not derived from either the first or the second class. However, the operator will return true because the class from which this object is derived inherits from Child. Link to original source: Operator instanceof
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION