The instanceof operator in Java is used to indicate at runtime whether an object is an instance of a particular class. instanceof indicates whether the object is an instance of this particular class or its subclass by returning a boolean.
instanceof in Java is is in .net!
Usage: result = object instanceof class Parameter: Result: Boolean type. Object: Required. Arbitrary object expressions. Class: Required. Any defined object class. Illustrate: If the object is an instance of the class, the instanceof operator returns true. If the object is not an instance of the specified class, or if the object is null, false is returned.
However, there is a difference between the compilation state and the running state of instanceof in Java:
In the compiled state, class can be the parent class, its own class, or child class of the object object. In these three cases, Java does not report an error when compiling.
In the running transition, class can be the parent class of the object object, its own class, not a child class. In the first two cases, the result is true, and the last one is false. However, when class is a subclass, the compilation will not report an error. The run result is false.
Example:
interface Person
public interface Person { public void eat();
}
Implement the People class
public class People implements Person { private int a=0; @Override public void eat() { System.out.println("======"+a);
}
}
Subcategory xiaoming:
public class xiaoming extends People { private String name;
@Override public void eat() { System.out.println("+++++++++");
}
}
main function
Note: The code in the above 2 places will not report an error when compiling.
Run result:
true
false
true
true
|