gpt4 book ai didi

Java继承结构问题

转载 作者:行者123 更新时间:2023-12-02 14:33:29 24 4
gpt4 key购买 nike

我刚刚实现了一些类:

public abstract class Job<T extends ViewerUnion>{
[...]
}

public abstract class ReturnValueJob<T, S extends ViewerUnion> extends Job<S> {
[...]
}

public class MyReturnJob extends ReturnValueJob<Foo, Baa> {
[...]
}

public class JobExecuter {
public static void execute(List<Job> jobList){
for(Job actJob: jobList){
actJob.startJob();
}
for(Job actJob: jobList){
actJob.awaitTimeoutOrFinish();
}
}
}

现在我想执行这段代码:

List<Job> list = new LinkedList<MyReturnJob>();
JobExecuter.execute(list);

但是 Java 在编译时给了我一些错误:

Type mismatch: cannot convert from LinkedList to List

我不知道为什么,因为 MyReturnJob正在继承Job 。如果我将列表的定义更改为 LinkedList<MyReturnJob> list = new LinkedList<MyReturnJob>();

JobExecuter.execute(list); 上抛出同样的错误

感谢您的帮助。

最诚挚的问候,直到

最佳答案

这里出了什么问题?

问题不在于 LinkedList 的更改至List ,但是包含类型发生了变化。 Java 泛型不是协变,这意味着您甚至不能这样做:

LinkedList<Job> = new LinkedList<MyReturnJob>();

详细信息...

有关更多信息,请阅读 "Java theory and practice: Generics gotchas"文章。这是其相关部分:

It turns out there's a good reason it doesn't work (...): It would break the type safety generics were supposed to provide. Imagine you could assign a List<Integer> to a List<Number>. Then the following code would allow you to put something that wasn't an Integer into a List<Integer>:

List<Integer> li = new ArrayList<Integer>();
List<Number> ln = li; // illegal
ln.add(new Float(3.1415));

...应用回上下文

文章示例代码可以翻译成这个问题的上下文,如下所示:

List<MyReturnJob> li = new LinkedList<MyReturnJob>();
List<Job> ln = li; // illegal
ln.add(new FooJob());

哪里FooJob声明为:

public abstract FooJob extends Job<ViewerUnion> {
[...]
}

关于Java继承结构问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6243622/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com