Attempting the following:
class Base {
public Base(){
}
}
class Derived extends Base {
}
public class Main
{
public static void main (String[] args)
{
Derived derived = (Derived) new Base();
}
}
Causes a CastClassException
, but compiles successfully. The comments on this question suggest that it's impossible for the compiler to figure out what type new Base()
has until runtime -- but why should that be the case? I know that in other type systems the compiler can always infer the type of any expression, and the Java compiler certainly does some type inference with e.g. lambda expressions. And it must, at some point, know what type new Base()
has if it's going to emit the correct bytecode.
Is there a theoretical limitation that prevents the Java compiler from catching this before the program runs, or is it an implementation choice?