Concept: 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.
Formula: Result = Object instanceof class
Parametric analysis:
Result: Boolean type
Object: An arbitrary instance or an expression
Class: Any one of the defined classes
Results Analysis:
Returns true if object is an instance of class, or false if not or if object is null
Instaanceof are different at run time and compile time:
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.
public class Base {
String name = "Base";
public void Basea () {
System.out.println ("name is" + name);
}
}
public class Child extends Base {
String name = "Child";
String age = "18";
}
public class Test {
public static void Main (string[] args) {
Base base = new Child ();
System.out.print (base instanceof Base);
System.out.print (base instanceof Child);
System.out.print (base instanceof Object);
System.out.print (base instanceof System); --Compilation errors
}
}
Understanding of instanceof Keywords in Java