Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't this cast generate a compiler warning?

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

like image 269
jontejj Avatar asked Dec 21 '22 02:12

jontejj


2 Answers

Javac only warns for unsafe casts when using generics. Here the compiler trusts you to know what you're doing :)

like image 158
Peter Svensson Avatar answered Jan 08 '23 11:01

Peter Svensson


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.

like image 36
Thomas Avatar answered Jan 08 '23 12:01

Thomas