I'm busy with the OCP certification and here I have an example of code:
This gives an ClassCastException, ok that can I understand. But I expect nt compile error at tjhe line "unicorn.add(new Dragon());" , because the list has the type "Unicorn" and you add an Dragon object? Or at least I should expect an runtime error at this line.
Java discards generic type arguments during compilation. At runtime, every List acts like a List<Object>. This is called type erasure.
On line 3, unicorns is declared as a List<Unicorn>. This is a hint to the compiler that you may only add Unicorn to the list, and not Dragon. If you tried to add a new Dragon to your list in the main() method, the compiler would print an error message.
On line 7, the list is declared as a raw List. Since the variable doesn't use any type bounds, the compiler doesn't perform any type checking for you inside the addUnicorn() method. At runtime line 8 also executes just fine because as I've mentioned above, at runtime every List acts like a List<Object> due to type erasure.
Stephan van Hulst wrote:. . . the compiler doesn't perform any type checking . . .
It should however issue a warning about the use of a raw type. When you return to the calling method and the get() call executes, the runtime performs an implicit cast to (Unicorn) and that cast fails with the exception you mentioned.