我有两个类,一个扩展了另一个。父类中的大多数函数返回其自身(在修改调用该函数的对象之后)或相同类型的新对象。子类应该共享这些函数,但是它应该返回子类型的对象。
解决这个问题的明显方法是重写每个函数并将它们转换为子类型的对象,但我不想每次创建子类时都这样做。
我做了一些搜索,找到了一些使用通用函数的解决方案。然而,这些要么需要额外的 Class<T>
参数或可能会导致类型转换错误。
有没有办法在父类中创建一个函数,使得父类型或子类型的对象可以返回自身或相同类型的对象?
最佳答案
The obvious solution to this issue is to just override every function and convert them into an object of the child type, but I don't want to do this every time I make a child class.
如果您有特殊方法来创建子类型的新实例,则可以在所有其他方法中重用该方法。您仍然需要在每个子类中重写这个方法,但这比重写每个方法要好:
public abstract class Parent<T extends Parent<T>> {
protected abstract T newInstance();
public T doSomething() {
T instance = newInstance();
// do something with instance
return instance;
}
public T doSomethingElse() {
// do something with this
return this;
}
}
public class Child extends Parent<Child> {
protected Child newInstance() {
return new Child();
}
}
Child.doSomething
现在返回一个 Child
,而无需覆盖 doSomething
。
关于java - 返回与函数调用者类型相同的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56436837/