The instanceof operator is used to determine whether an object referenced by a reference type is an instance of a class.
The operation element on the left of the instanceof operator is a reference type (not a basic type), and the operation element on the right is a class name or interface name.
The format is as follows:
OBJ instanceof classname
Or
OBJ instanceof interfacename
For example:
Dog dog = new dog ();
System. Out. println (DOB instanceof XXX); // XXX indicates a class name or interface name.
An instance of a class includes an instance of the class itself and all instances of direct or indirect subclasses. Therefore, when "XXX" is the following value, the value of the instanceof expression is true.
● Dog
● Direct or indirect parent class of the Dog class
● Interfaces implemented by the dog class and all interfaces implemented by the parent class
Note:
1. instanceof accepts null and returns false.
2. The operation element on the left of instanceof is displayed as the declared type and must be of the same type or inheritance relationship with the operation element on the right, that is, it is located on the same inheritance branch of the inheritance tree; otherwise, the compilation fails.
For example:
Public class main {
Public static void main (string [] ARGs ){
String S = NULL;
System. Out. println (null instanceof string); // false
System. Out. println (s instanceof string); // false S is null
System. Out. println (s instanceof person); // An error occurred while compiling, not in the same branch of the inheritance tree.
Boolean B = false;
String STR = "foo ";
B = (STR instanceof string); // true
B = (STR instanceof object); // also true
B = (STR instanceof date); // compilation error, not located on the same branch of the inheritance tree.
}
}
3. instanceof can be used for array type
For example:
Boolean b1 = new int [4] instanceof long []; // a compilation error occurs. The types are inconsistent, meaning there is no inheritance relationship.
Boolean b2 = new int [4] instanceof int []; // valid. The value of B2 is true.