Java Instanceof Class: This tutorial will teach you all about the Instanceof in java operator, including how to use it with examples. If you want to check if an object is an instance of a specific type (Interface, Class, or Subclass), you can use the java instanceof operator. Based on the comparison it will give the result as true or false.
If you try to compare any object instance with type with the help of Instanceof in java then you will get the output result as FALSE.
Post Type: | Java Programs Tutorial |
Published On: | www.softwaretestingo.com |
Applicable For: | Freshers & Experience |
Get Updates: | Join Our Telegram Group |
Java Instanceof Example
package com.softwaretestingo.basic; public class InstanceOfEx1 { public static void main(String[] args) { InstanceOfEx1 obj=new InstanceOfEx1(); System.out.println(obj instanceof InstanceOfEx1); } }
Instanceof in java during Inheritance
The instanceof operator allows us to check the object of a subclass is an instance of a superclass or not.
package com.softwaretestingo.basic; class abc{} public class InstanceOfEx2 extends abc { public static void main(String[] args) { InstanceOfEx2 obj=new InstanceOfEx2(); System.out.println(obj instanceof InstanceOfEx2); System.out.println(obj instanceof abc); } }
Java instanceof in Interface
The purpose of the instanceof operator is to check if an object belongs to a certain class or interface. It returns true if the object is indeed an instance of that class/interface.
package com.softwaretestingo.basic; interface intef { } class test1 implements intef { } public class InstanceOfEx3 extends test1 { public static void main(String[] args) { InstanceOfEx3 obj=new InstanceOfEx3(); System.out.println(obj instanceof intef); } }
Conclusion:
In this blog post, we have tried to cover the Java InstanceOf Keyword operator in detail with an example. Let me know if you find something is missing about the Java InstanceOf then you can inform us by a comment in the comment section.
Leave a Reply