![]() |
VOOZH | about |
The instanceof keyword is used to check whether an object belongs to a specific class, subclass, or interface. It compares an object reference with a type and returns a boolean value (true or false). This keyword is commonly used to verify an object's type before performing typecasting, helping to avoid runtime errors such as ClassCastException.
objectReference instanceof ClassName
true
Explanation: This program creates an object of the GFG class and checks whether it belongs to the same class using the instanceof keyword. Since the object is created from GFG, the condition returns true.
Here are all the examples of instanceof keywords with their respective cases:
Example: Reating sample classes with a parent-child relationship.
cobj is instance of Child cobj is instance of Parent cobj is instance of Object
Explanation: A Child object is created and tested against Child, Parent, and Object classes. Since a child object inherits from its parent and every class inherits from Object, all checks return true.
Example: Instanceof returning false for null
tobj is NOT instance of Test
Explanation: The reference variable tobj is assigned null and checked using instanceof. Since null does not refer to any object, the expression returns false
Example: Parent object is not an instance of Child
pobj is NOT instance of Child
Explanation: A Parent object is created and checked whether it is an instance of Child. Since a parent object cannot be treated as a child object, the result is false.
Example: Parent reference referring to a Child is an instance of a Child
cobj is instance of Child
Explanation: A parent reference variable stores a Child object. Although the reference type is Parent, the actual object is Child, so instanceof Child returns true.
Example: Java program to demonstrate that non-method members are accessed according to reference type (Unlike methods which are accessed according to the referred object)
Value accessed through parent reference with typecasting is 10
ClassCastException by validating object types before casting.