Reputation: 1313
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
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 Object
s 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