-2
interface P{}

class A{}

class Demo{
    public static void main(String arg[]){
        A a1=null;
        P p1=null;
        
        a1=(A)p1; //legal
        p1=(P)a1; //legal
    }
}

In this code, the interface P and the class A a are not in the same hierarchy but statements typed to cast interface to class and class to interface are legal. So why this is legal?

Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
  • Because you can cast anything to anything. Casting is saying you explicitly know something will work. Have you tried to run it? You'll get an error at runtime. Or you would if they weren't null- null can successfully cast to anything. – Gabe Sechan Aug 08 '22 at 05:37
  • Title is vague. Rewrite to summarize your specific technical issue. – Basil Bourque Aug 08 '22 at 05:40
  • Because null has no type this will compile and run without exception. You can cast anything to anything, but if the value is not of type cast or an inheritor or implementor of it, it will result in a runtime failure. But null is a typeless value. – Hafthor Aug 08 '22 at 05:41
  • 1
    @GabeSechan Well, not "anything to anything". If the compiler can statically prove that a cast is impossible, then the code will fail to compile. The key word there is "statically". It depends entirely on the static types of the variables, not the run-time types of the referenced objects. For instance, if `P` were a class instead of an interface, then the above would fail, because in that case an object could never be both an `A` and a `P`. But since `P` is an interface, the cast _could_ possibly succeed (from the compiler's perspective, anyway). – Slaw Aug 08 '22 at 05:49

1 Answers1

2

Because the runtime type of a1 and p1 can be a subclass of A that implements P.

daniu
  • 14,137
  • 4
  • 32
  • 53