usage:
(type variable instanceof class | interface)
effect:
The instanceof operator is used to determine whether the previous object is an instance of the following class, or its subclass or implementation class. If so, return true; otherwise, return false.
Notice:
・The compile-time type of the operand in front of instanceof is either the same as the following class, or has a parent-child inheritance relationship with the following class, otherwise a compilation error will occur.
A simple example:
Copy the code code as follows:
/**
* instanceof operator
* @author Administrator
*
*/
public class TestInstanceof {
public static void main(String[] args) {
//Use the Object class when declaring hello, then the compiled type of hello is Object
//Object class is the parent class of all classes, but the actual type of hello is String
Object hello = "Hello";
//String is a subclass of Object and can perform instanceof operation and return true
System.out.println("Is the string an instance of the object class:"
+ (hello instanceof Object));
//true
System.out.println("Is the string an instance of String:"
+ (hello instanceof String));
//false
System.out.println("Is the string an instance of the Math class:"
+ (hello instanceof Math));
//String implements the Comparable interface, so it returns true
System.out.println("Is the string an instance of the Comparable class:"
+(hello instanceof Comparable));
/**
* String is neither the Math class nor the parent class of the Math class, so the following code compiles incorrectly
*/
//String a = "hello";
//System.out.println("Is the string an instance of the Math class:"
// + (a instanceof Math));
}
}
Running results:
Copy the code code as follows:
Whether the string is an instance of the object class: true
Whether the string is an instance of String: true
Whether the string is an instance of the Math class: false
Whether the string is an instance of the Comparable class: true
Usually before performing forced type conversion, it is first determined whether the previous object is an instance of the latter object and whether the conversion can be successful, thereby ensuring the robustness of the code.