instanceof is a keyword that is used for checking if a reference variable is containing a given type of object reference or not.
Following is a Java program to show different behaviors of instanceof.
cobj is instance of Child cobj is instance of Parent cobj is instance of Object
instanceof returns false for null
tobj is NOT instance of Test
A parent object is not an instance of Child
pobj is NOT instance of Child
A parent reference referring to a Child is an instance of Child
cobj is an instance of Child
We have seen here that a parent class data member is accessed when a reference of parent type refers to a child object. We can access child data member using type casting.
Syntax: ((child_class_name) Parent_Reference_variable).func.name().
When we do typecast, it is always a good idea to check if the typecasting is valid or not. instanceof helps us here. We can always first check for validity using instancef, then do typecasting.
Value accessed through parent reference with typecasting is 10
This article is contributed by Twinkle Tyagi .If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important Java and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.
- Using throw, catch and instanceof to handle Exceptions in Java
- instanceof operator vs isInstance() method in Java
- Containerizing Java applications | Creating a Spring Boot App using Dockerfile
- Java.lang.Integer class and its methods
- java.math class and its methods | Set 1
- java.math class and its methods | Set 3
- Maximum element in an array such that its previous and next element product is maximum
- Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
- Java.util.TreeMap.firstEntry() and firstKey() in Java
- Java.util.TreeMap.containskey() and containsValue() in Java
- Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
- Java.util.TreeMap.put() and putAll() in Java
- Java.util.TreeMap.floorEntry() and floorKey() in Java
- Java Swing | Translucent and shaped Window in Java
- Difference between Core Java and Advanced Java
- Difference between a Java Application and a Java Applet
- Difference between Java IO and Java NIO
- Difference between Java and Core Java
- Difference and similarities between HashSet, LinkedHashSet and TreeSet in Java
- Similarities and Difference between Java and C++