Why does this throw not generate a compiler warning?

Why doesn't the following java code generate a compiler warning saying something like "Insecure listing 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 also does not warn about this.

Instead, it raises an exception at runtime:

Exception in thread "main" java.lang.ClassCastException: SuperClass $ AnotherBaseClass cannot be attributed to SuperClass $ SomeBaseClass

+4
source share
3 answers

Actually, the compiler will throw an error if a throw is not possible at all, for example. if the return type of the create() method will be AnotherBaseClass instead of SuperClass .

Since it returns SuperClass , the compiler does not know what will actually be returned, it can also return SomeBaseClass . Therefore, he must believe that you know what you are doing with this act.

Edit:

To get a warning when casting, you can try using a code analysis tool like Checkstyle . Note, however, that these tools most likely cannot or do not check the class hierarchy and, therefore, can only be able to warn the (non-primitive) casts used in general. That way, if you use a library that needs drops (for example, if you use a collection of apache collections that does not yet support generics), you will get many warnings.

After all, programming is still an art, and you still need to know what you are doing.

+3
source

Javac warns only about unsafe ghosts when using generics. Here the compiler trusts you to know what you are doing :)

+8
source

This is not a compiler warning. It failed at runtime while trying to apply AnotherBaseClass to SomeBaseClass .

0
source

Source: https://habr.com/ru/post/1393253/


All Articles