Use of the Java instanceof operator
- 2020-04-01 01:27:52
- OfStack
Usage:
(type variable instanceof class | interface)
Function:
The instanceof operator is used to determine whether the preceding object is a subsequent class or an instanceof its subclass or implementation class. Returns true if yes or false.
Note:
, the compile-time type of the operands preceding instanceof is either the same as the following class or has a parent-child inheritance relationship with the latter class or it will cause a compilation error.
A simple example:
public class TestInstanceof {
public static void main(String[] args) {
//When you declare hello using the Object class, the compile type of hello is Object
//The Object class is the parent of all classes, but the actual type of hello is String
Object hello = "Hello";
//String is a subclass of Object and you can do the instanceof operation and return true
System.out.println(" Is the string object Class instance: "
+ (hello instanceof Object));
//true
System.out.println(" Is the string String Examples: "
+ (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 Comparable Class instance: "
+(hello instanceof Comparable));
//String a = "hello";
//System.out.println(" is the string an instance of the Math class:"
// + (a instanceof Math));
}
}
Operation results:
Is the string object Class instance: true
Is the string String Examples: true
Is the string Math Class instance: false
Is the string Comparable Class instance: true
Typically, before casting, the code is robust by determining whether the previous object is an instance of the next object and whether it can be successfully converted.