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
Javac only warns for unsafe casts when using generics. Here the compiler trusts you to know what you're doing :)
Actually, the compiler would throw an error if the cast was not possible at all, e.g. if the create()
methods return type would be AnotherBaseClass
instead of SuperClass
.
Since it returns a SuperClass
the compiler doesn't know what will actually be returned - it could as well return a SomeBaseClass
. 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With