Search code examples
javainstanceof

Instanceof does not show compile error with interface, but with abstract class does


I think the title is self explanatory. So suppose I have this code:

interface A { }

abstract class B { }

class C { }

C c = new C();

System.out.println(c instanceof A); //fine
System.out.println(c instanceof B); // compile error

In a comment from the question I read this:

The compiler can never know whether a given type doesn't implement an interface because a potential subclass could implement it.

So if for interface this works, why it should not work for an abstract class ? It also should be extended by some other class, as it can't exist by it's own. Can someone clarify this?

Update Compile message:

Error:(22, 28) java: incompatible types: C cannot be converted to B


Solution

  • It is simple: C extends Object. No subclass of C could possible extend B. You can't add another base class, because Java doesn't support multiple inheritance.

    Whereas a subclass of C can very well implement that additional interface. But there is simply no way how a C object could also be a B instance.

    So:

    D extends C implements B // obviously all fine
    

    whereas

    D extends B extends C 
    

    is impossible. Because B is already defined to not extend anything but Object. Of course, the "trick" here is that both classes B, C are both known, and as said: C isn't extending B.