Java instanceof Keyword Usage Detailed Explanation and Points for Attention

  • 2021-11-13 07:54:44
  • OfStack

instanceof is strictly a binocular operator in Java, which is used to test whether an object is an instance of a class. Its usage is:


boolean result = obj instanceof Class

obj is an object, and Class represents a class or an interface. When obj is an object of Class, or its direct or indirect subclass, or its interface implementation class, result returns true, otherwise it returns false.

Note: The compiler will check whether obj can be converted to the right class type. If it cannot be converted, it will report an error directly. If the type cannot be determined, it will be compiled, depending on the runtime.

instanceof

instanceof is a reserved keyword of Java, with objects on the left and classes on the right, and the return type is Boolean type. Its specific function is to test whether the object on the left is an instance object created by the class on the right or a subclass of the class. If so, it returns true, otherwise it returns false.

Matters needing attention in the use of instanceof

There is inheritance relationship first, and then there is the use of instanceof. When the test object is created, any one of the declared type on the right and the class on the left must be the same branch of the inheritance tree or have an inheritance relationship with the test class, otherwise the compiler will report an error.

instanceof Use Sample


public class Application {

  public static void main(String[] args) {

    // Object > Person > teacher
    // Object > Person > Student
    // Object > String
    Object o = new Student(); //  It mainly depends on what type this object is and the name of the instantiated class 
    // instanceof Keyword can determine whether the left object is of the right class or subclass 1 Instances 
    System.out.println(o instanceof Student); // o  Yes Student Class 1 Instance object   So judge the right class heel student There is no relationship   And whether the display declaration has a relationship 
    System.out.println(o instanceof Person); // true
    System.out.println(o instanceof Object); // true
    System.out.println(o instanceof String); // false
    System.out.println(o instanceof Teacher); //  Irrelevant 
    System.out.println("========================");
    Person person = new Student();
    System.out.println(person instanceof Person); // true
    System.out.println(person instanceof Object); // true
    // System.out.println(person instanceof String); //  Compilation error 
    System.out.println(person instanceof Teacher); //  Irrelevant 

  }
}

instanceof Application Scenarios

When you need to use the cast of objects, you need to use instanceof for judgment.


Related articles: