我一直在努力尝试覆盖通用抽象类中的方法。
public abstract class Grandparent<T extends Grandparent>
public T set(final T other) //does stuff I don't want to do
public abstract class Parent<T extends Parent<T>> extends Grandparent<T>
public T set(final Parent<?> other) // does stuff I want to do
所有的子类都扩展父类 <child>
.
但是,我无法通过仅构造其中一个子类来调用我想要的 set() 函数。
Child_1 test = new Child_1();
Child_1 test_2 = new Child_1();
test.set(test_2) //this calls the function I don't want
Parent<Child_1> test_3 = new Child_1();
Parent<Child_1> test_4 = new Child_1();
test3.set(test_4) //this calls the function I do want
但是,这需要修改现有代码。很多。我不想将 set 方法重写为
public T set(T other)
因为那样的话我将失去从另一个子类对象设置一个子类对象的能力。
如何编写 set() 方法以在子对象调用它时触发它,并传入任何其他子对象,而不对外部代码进行任何修改?
最佳答案
要覆盖方法,您需要提供一个覆盖等效 签名,这意味着方法名称和参数的数量和类型必须相等。 Grandparent.set()
和 Parent.set()
不是这种情况。因此,Parent.set()
重载而不是覆盖 Grandparent.set()
。
我看到的最简单的解决方案是将方法签名概括如下:
public abstract class Grandparent<T extends Grandparent>
public T set(Grandparent<?> other)
public abstract class Parent<T extends Parent<T>> extends Grandparent<T>
public T set(Grandparent<?> other)
那样的话,方法就会被覆盖,而您不必修改任何子类。
关于java - Java 中的方法覆盖和泛型问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3702268/