【发布时间】:2020-09-07 18:32:02
【问题描述】:
这个问题是关于接口与实现该接口的类的关系。我看不出this 或this 是如何回答问题的。
我创建了一个接口Boxed 和一个抽象泛型类Box,它实现了该接口。然后我创建了两个具体的类IntegerBox 和StringBox。然后我创建了一个元素列表,它使用IntegerBox 值和StringBox 值扩展Box。到目前为止一切顺利。
现在我想将List<? extends Box> 分配给List<Boxed>。我的期望是,这应该是有效的,因为任何扩展 Box 也实现了 Boxed。但是编译器不允许我。这是错误:
main.java:29: error: incompatible types: List<CAP#1> cannot be converted to List<Boxed>
List<Boxed> lb2 = laeb; // does not compile, although every value which extends Box implements Boxed
^
where CAP#1 is a fresh type-variable:
CAP#1 extends Box from capture of ? extends Box
1 error
我可以复制列表:
List<? extends Box> laeb = List.of (new IntegerBox(42), new StringBox("answer"));
List<Boxed> lb1 = new ArrayList<> (laeb);
如果类型为Boxed,则? extends Box 类型的每个元素都用于创建一个值。但是分配报告了不兼容的类型。为什么?
import java.util.List;
import java.util.ArrayList;
public class main
{
static interface Boxed { }
static abstract class Box<T> implements Boxed
{
T content;
Box (T content) { this.content = content; }
}
static class IntegerBox extends Box<Integer> { IntegerBox (Integer content) { super (content); } }
static class StringBox extends Box<String> { StringBox (String content) { super (content); } }
public static void main (String ...arguments) throws Exception
{
IntegerBox i = new IntegerBox(42);
StringBox s = new StringBox("answer");
List<? extends Box> laeb = List.of (i, s);
Boxed b0 = i; // => IntegerBox is compatible with Boxed
Boxed b1 = s; // => StringBox is compatible with Boxed
List<Boxed> lb1 = new ArrayList<> (laeb); // List<Boxed> can be created by values of "? extends Box"
List<Boxed> lb2 = laeb; // does not compile, although every value which extends Box implements Boxed
}
}
【问题讨论】:
标签: java