The instanceof operator in Java is used to indicate at run time whether an object is an instance of a particular class. Instanceof Indicates whether this object is an instance of this particular class or its subclasses by returning a Boolean value.
Usage:
Result = Object Instanceof class
Parameters:
Result: Boolean type.
Object: Required option. An arbitrary object expression.
Class: Required option. Any of the defined object classes.
Description
If object is an instance of class, the instanceof operator returns TRUE. Returns False if object is not an instance of the specified class, or if object is null.
However, there is a difference between the instanceof in Java and the running state:
In the compilation state, the class can be the parent class of the object, its own class, and the subclass. In these three cases, Java compiles without error.
In the run-to-state, the class can be the parent class of object objects, its own class, and cannot be a subclass. In the first two cases, result is true and the last is false. But when class is a subclass, compilation does not give an error. The run result is false.
Example:
Interface person
Public interface Person {
public void eat ();
}
Implementing class people
Public class people implements person {
private int a=0;
@Override
public void Eat () {
System.out.println ("======" +a);
}
}
Sub-class Xiaoming:
Public class Xiaoming extends people {
private String name;
@Override
public void Eat () {
System.out.println ("+++++++++");
}
}
Main function
public static void Main (string[] args) {
People p=new people ();
Xiaoming x=new xiaoming ();
SYSTEM.OUT.PRINTLN (P instanceof person);
SYSTEM.OUT.PRINTLN (P instanceof xiaoming); -----2
SYSTEM.OUT.PRINTLN (x instanceof person);
SYSTEM.OUT.PRINTLN (x instanceof people);
}
Note: The code above 2 does not error at compile time.
Operation Result:
True
False
True
True
Understanding of instanceof Keywords in Java