java - 抽象类如何返回子类对象的 ArrayList?
问题描述
我正在尝试返回子类对象的数组列表
认为
abstract class Foo {
protected abstract ArrayList<Foo> getAlotOfMyself();
};
是一个超类,它的子类需要返回自己的数组,例如它的子类:
class Bar extends Foo{
public ArrayList<Bar> getAlotOfMyself(){
// Do the interesting stuff
}
};
但是,由于java,这不起作用,即使是子类ArrayList<Foo>
也不相同ArrayList<Bar>
Bar
Foo
我已经尝试将 Foo 中的 ArrayList 更改为,ArrayList<? extends Foo>
但它似乎只在 Foo 不是抽象类(因此getAlotOfMyself()
在 中实现Foo
)时才有效,它不会编译说 :
cannot convert from ArrayList<capture#1-of ? extends Foo> to ArrayList<Foo>
。
导致该错误的原因是这个
void interestingFunction(Foo foo){
ArrayList<Foo> alot = foo.getAlotOfMyself(); // the compile error happens here
}
当然这个函数只在Bar
和其他子类上调用
解决方案
试试这个,看看它是否符合您的要求。
import java.util.ArrayList;
import java.util.List;
public class SubclassStuff {
public static void main(String[] args) {
Bar b = new Bar();
b.interestingFunction(b);
}
}
abstract class Foo {
public String name;
public Foo() {
}
public Foo (String name) {
this.name = name;
}
protected abstract ArrayList<? extends Foo> getAlotOfMyself();
public void interestingFunction(Foo foo) {
System.out.println(foo.getAlotOfMyself());
}
}
class Bar extends Foo {
public ArrayList<Bar> getAlotOfMyself() {
return new ArrayList<>(List.of(new Bar("I am Bar")));
}
public Bar() {
super();
}
public Bar (String name) {
this.name = name;
}
public String toString() {
return name;
}
}
推荐阅读
- csv - 从 awk 解析文件时发生错误
- java - 如何将响应式 imageView 设置为所有尺寸?
- r - Shiny 应用程序在 Shiny 服务器上的运行速度比在本地运行时慢得多
- react-native - 在 WebStorm 中使用 React Native 为调试器附加 Chrome 浏览器时出现问题
- angular - Angular Injectable 装饰器 - 预期 0 个参数,但得到 1 个
- vba - URLDownloadToFile 无法正常工作
- c# - 用 C# 在 FTP 服务器上创建 PDF
- c# - 如何使用多种简单类型 PostAsync()?
- codenameone - 访问手机设置:codeName one
- angular - Angular 5在http get请求中正确传递标头