Java – why can’t I use multiple type parameters with wildcards?

For example, why can't I do this (I1 and I2 are two interfaces):

List<? extends I1 & I2> myList;

Note that I don't want to add a new interface that extends I1 and I2 because it has no additional functionality and is just a placeholder

Solution

Two reasons:

The first is because Java does not support multiple inheritance

The second is because this means that you cannot return objects with multiple types

For example, imagine mylist Get (I) method What return type should you have in your example? It must be I1 or I2, it cannot be both

You can define an interface that implements I1 and I2 and then use it – but all objects added to the list need to implement the new interface Adding something that implements I1 and I2 but is not a new interface is still invalid

Forget the generics and try to write a that returns I1 and I2 Get () method stub - you can't do this, it's illegal in Java Generics do not allow you to do this because there is no way to convert the generated code into legitimate java code A more detailed discussion of why Java only supports single inheritance because it is part of a larger discussion

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>