首页 > 解决方案 > 抽象类如何返回子类对象的 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>BarFoo

我已经尝试将 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和其他子类上调用

标签: javagenericsarraylist

解决方案


试试这个,看看它是否符合您的要求。

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;
    }
}

推荐阅读