instance vs instanceof Java

instance vs instanceof Java

instance vs instanceof: Both are very confusing words and few people know about instanceof. Let make the concept crystal clear.

A) instance:

Everyone knows what an instance is. Any OOPs guy says, "an instance of a class is known as object". At an outset, instance and object one and the same. By the by, instance is not a keyword of Java.

In the above code, d1 is known as instance or object of class Demo. Is there any way, in Java, to check d1 is really an instance of Demo class? Yes, there is. Use instanceof keyword. The next explanation says.

B) instanceof:

instanceof is a keyword of Java used to check whether a particular object belongs to which class. instanceof evaluates to true when an object belongs to a specific class.


instance vs instanceof Java
Output Screenshot on instance vs instanceof Java

In the above code, str1 is an instance of class String. For this reason. "str1 instanceof String" printed true. Similarly with StringBuffer and Demo classes also.

instanceof evaluation also gives true even with its super class. The super class of String is Object class. That is, "str1 instanceof Object" also prints true. It is more clear in the next program.


instance vs instanceof Java
Output Screenshot on instance vs instanceof Java

Demo class super class is Test class. d1 is an object of Demo class. "d1 instanceof Demo" and "d1 instanceof Test", both print true.

What Java rule says:

An instance of a class is also an instance of its super classes. By this rule, every instance of any Java class is also an instance of Object class. Here, d1 instance (or object) of Demo class is also an instance of its super class Test (and also of Object, not shown in the code).

View All for Java Differences on 90 Topics

Leave a Reply

Your email address will not be published. Required fields are marked *