The instanceof operator in Java is used to check whether an object belongs to a specific class or its subclass. It accepts an object reference and a class object, and returns true or false according to whether the object belongs to the class or its subclass. Commonly used on type checking, polymorphism, and class hierarchies.
The role of instanceof operator in Java
The instanceof operator is a binary operator used to check Whether an object belongs to a specific class or its subclasses. It receives two operands: an object reference and a class object.
Syntax
<code class="java">boolean instanceofResult = objectReference instanceof classObject;</code>
Return value
If objectReference belongs to classObject or its subclass, the instanceof operator returns true; otherwise Return false.
Usage scenarios
The instanceof operator is usually used in the following scenarios:
Instance
The following are some examples of the instanceof operator:
<code class="java">Object object = new Object(); boolean isObject = object instanceof Object; // true Animal animal = new Dog(); boolean isDog = animal instanceof Dog; // true boolean isAnimal = animal instanceof Animal; // true</code>
It should be noted that the instanceof operator only checks the object's actual type without checking its declared type. Therefore, the following code returns true even though the object variable is declared as type Object:
<code class="java">Object object = new String(); boolean isObject = object instanceof Object; // true boolean isString = object instanceof String; // true</code>
By using the instanceof operator, you can efficiently check the type of an object and perform appropriate operations in your code.
The above is the detailed content of The role of instanceof in java. For more information, please follow other related articles on the PHP Chinese website!