The compiler, according to the specification, only considers the declared type a when it performs these checks for translations.
So you write:
A a = new A();
But the compiler only takes into account
A a;
So, he knows that a cannot be a String , since a class can have only one superclass (without multiple inheritance), there cannot be a subclass of a , which is also a string.
But for interfaces, this is not true. Therefore, although we know that class a does not implement List , there may exist class B defined as follows:
class B extends A implements List {}
And since the compiler only considers the declared type, it must assume that you can also assign new B() a .
So, since subclass a can implement the List interface, the compiler cannot assume that casting to List always fails.
Of course, the order will be unsuccessful in practice, although at runtime. But not at compile time.
source share