Java - 继承 - 您可以将子self返回到返回self的父实例方法吗?

时间:2017-08-17 23:52:20

标签: java inheritance arraylist

我基本上有自己的自定义列表,它有一堆功能,但由于我操作相同类型的列表,我想用定义的类型扩展这个自定义列表,并希望能够使用父函数并返回孩子类型。

示例:

//Object within the list
public class ChildObject {

    private string name;

    // getters, setters, methods, etc.
}


// Parent custom list
public class ParentList<T> extends ArrayList<T> {

    public ParentList<T> filter(Predicate<T> predicate) {
        Collector<T, ?, List<T>> collector = Collectors.toList();

        List<T> temp = this.stream().filter(predicate).collect(collector);

        this.clear();
        this.addAll(temp);

        return this;
    }
}

// Extended custom list with predefined type
public class ChildList extends ParentList<ChildObject> {

    // other methods
}

// implementation
public static void main(String[] args) {

    ChildObject a = new ChildObject("Alice");
    ChildObject b = new ChildObject("Bob");

    ChildList filterList = new ChildList();
    filterList.add(a);
    filterList.add(b);

    filterList.filter(c -> childObject.getName().equals("Alice"));
}

如果这是可能的,那将是非常好的,但是可以自由地说明这是否可行,实用,或对性能问题或不良做法有任何想法。

1 个答案:

答案 0 :(得分:0)

我确实找到了一个解决方案,但我想知道如果没有以下解决方案,它们是否可以使其工作:

// Extended custom list with predefined type
public class ChildList extends ParentList<ChildObject> {

    public ChildList filter(Predicate<ChildObject> predicate) {
        super.filter(predicate);

        return this;
    }

    // other methods
}