Why doesn’t the following java code generate a compiler warning saying something like “Unsafe cast from SuperClass to SomeBaseClass”?
public abstract SuperClass
{
static SuperClass create()
{
return new AnotherBaseClass();
}
private static class SomeBaseClass extends SuperClass
{
void print()
{
System.out.println("Hello World");
}
}
private static class AnotherBaseClass extends SuperClass
{
}
public static void main(String[] args)
{
SomeBaseClass actuallyAnotherClass = (SomeBaseClass)SuperClass.create();
actuallyAnotherClass.print();
}
}
I used jdk1.6.0_25/bin/javac on a Windows machine. Eclipse Helios doesn’t warn about it either.
Instead it results in a runtime exception:
Exception in thread “main” java.lang.ClassCastException: SuperClass$AnotherBaseClass cannot be cast to SuperClass$SomeBaseClass
Actually, the compiler would throw an error if the cast was not possible at all, e.g. if the
create()methods return type would beAnotherBaseClassinstead ofSuperClass.Since it returns a
SuperClassthe compiler doesn’t know what will actually be returned – it could as well return aSomeBaseClass. Thus it has to trust that you know what you do with that cast.Edit:
To get a warning when casting you might try and employ a code analysis tool like Checkstyle.
Note, however, that those tools most likely can’t or don’t check the class hierarchy and thus might only be able to warn about (non-primitive) casts being used in general. Thus if you use a library that requires casts (e.g. if you’re using apache commons collections which doesn’t support generics yet) you’d get a lot of warnings.
After all, programming is still an art and you still need to know what you’re doing.