Java - 继承 - 是否可以将子 self 返回到返回 self 的父实例方法中?



我基本上有自己的自定义列表,它具有很多功能,但由于我正在操作相同类型的列表,因此我想使用定义的类型扩展此自定义列表,并希望能够使用父函数并返回子类型。

例:

//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"));
}

如果这是可能的,那就太好了,但请随时说明这是否可行、实用,或者对性能问题或不良做法有任何想法。

我确实想出了一个解决方案,但我想知道是否有任何方法可以在没有以下解决方案的情况下使其工作:

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

最新更新