instanceof Keyword in Java
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. Henceforth it is known as a comparison operator where the instance is getting compared to type returning boolean true or false as in java we do not have 0 and 1 boolean return types.
Implementation: Here we will be creating sample classes with a parent-child relationship.
cobj is instance of Child cobj is instance of Parent cobj is instance of Object
Example 2: instanceof returning false for null
tobj is NOT instance of Test
Example 3: Parent object is not an instance of Child
pobj is NOT instance of Child
Example 4: Parent reference referring to a Child is an instance of Child
cobj is an instance of Child
Now, the application of instanceof keyword is as follows:
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 write.geeksforgeeks.org or mail your article to email@example.com. 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 Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.