Reputation: 2840
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
Upvotes: 4
Views: 226
Reputation: 88707
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.
Upvotes: 3
Reputation: 51030
That's not a compiler warning. It has failed at runtime while trying to cast AnotherBaseClass
object to SomeBaseClass
.
Upvotes: 0
Reputation: 6173
Javac only warns for unsafe casts when using generics. Here the compiler trusts you to know what you're doing :)
Upvotes: 8