简体   繁体   中英

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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM