AntonBoarf
AntonBoarf

Reputation: 1313

Java SE : generics and inheritance/polymorphism

I have a class Message and a list of message : List<Message> messages

I cannot do List<Object> objects = messages; I know that.

But I can do this without compilation errors :

Object object = messages;
List<Object> myList = (List<Object>) object;
myList.add(new Object());

Then my messages list can contain any object and not just Message objects. Why is that ?

Upvotes: 1

Views: 57

Answers (1)

Konstantin Yovkov
Konstantin Yovkov

Reputation: 62874

Casting messages to a List<Object> will make your essential Message instances be treated like Object instances and nothing more (at Runtime).

Additionally, you can somewhere cast these Objects back to Message, but the compiler cannot give any guarantees that you won't get a ClassCastException at Runtime (because it could be that you pick the new Object() instance and try to cast it to Message)

That's actually the reason why myList.add(new Object()) compiles - the compiler doesn't complain, because that added instance conforms the content definition of myList.

Not related to your question problem, but probably worth mentioning is that the casting operation is actually highly discouraged, as it's an indicator of a poor object design.

Upvotes: 1

Related Questions