Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The 'instanceof' operator behaves differently for interfaces and classes

I would like to know regarding following behavior of instanceof operator in Java.

interface C {}  class B {}  public class A {     public static void main(String args[]) {         B obj = new B();         System.out.println(obj instanceof A);      //Gives compiler error         System.out.println(obj instanceof C);      //Gives false as output     } } 

Why is it so? There is no relation between interface C and class B, but it gives false whereas in case of obj instanceof A it gives compiler error?

like image 926
Ajay Sharma Avatar asked Jul 14 '15 05:07

Ajay Sharma


People also ask

Does Instanceof work for interfaces?

instanceof can be used to test if an object is a direct or descended instance of a given class. instanceof can also be used with interfaces even though interfaces can't be instantiated like classes.

Can a class be an Instanceof an interface?

Yes it is correct. you can do it with an inner class. This seems the most correct of the answers, even though there is no explanation. For you Android programmers, Google provides an example of an class instantiating an inner interface here.

What does the Instanceof operator do?

The instanceof operator in Java is used to check whether an object is an instance of a particular class or not. objectName instanceOf className; Here, if objectName is an instance of className , the operator returns true . Otherwise, it returns false .

What is the difference between class isInstance and Instanceof operator?

The instanceof operator and isInstance() method both are used for checking the class of the object. But the main difference comes when we want to check the class of objects dynamically then isInstance() method will work. There is no way we can do this by instanceof operator.


1 Answers

Because Java has no multiple class inheritance it's absolutely known during the compilation that obj object of type B cannot be subtype of A. On the other hand it possibly can be subtype of interface C, for example in this case:

interface C {}  class B {}  class D extends B implements C {}  public class A {     public static void main(String args[]) {         B obj = new D();         System.out.println(obj instanceof C);      //compiles and gives true as output       } } 

So looking only at obj instanceof C expression compiler cannot tell in advance whether it will be true or false, but looking at obj instanceof A it knows that this is always false, thus meaningless and helps you to prevent an error. If you still want to have this meaningless check in your program, you can add an explicit casting to the Object:

System.out.println(((Object)obj) instanceof A);      //compiles fine 
like image 185
Tagir Valeev Avatar answered Sep 17 '22 17:09

Tagir Valeev