简体   繁体   English

Java SE:泛型和继承/多态

[英]Java SE : generics and inheritance/polymorphism

I have a class Message and a list of message : List<Message> messages我有一个class Message和一个消息List<Message> messagesList<Message> messages

I cannot do List<Object> objects = messages;我不能做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.然后我的messages列表可以包含任何对象,而不仅仅是消息对象。 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).messages投射到List<Object>将使您的基本Message实例被视为Object实例,仅此而已(在运行时)。

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 )此外,您可以在某处将这些ObjectMessage ,但编译器无法保证您在运行时不会收到ClassCastException (因为可能是您选择了new Object()实例并尝试将其转换为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 .这实际上是myList.add(new Object())编译的原因 - 编译器不会抱怨,因为添加的实例符合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.与您的问题无关,但可能值得一提的是,实际上非常不鼓励强制转换操作,因为它表明对象设计不佳。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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