英文:
Abstract method is not considered implemented when using Child class as return types
问题
I have the classes
abstract class A<T> {
public abstract A<T> someFunction(A<?> obj);
}
public class B extends A<Integer>{
public B someFunction(B obj){...}
}
我得到一个错误,提示说Class B must be declared abstract or must implement the abstract method someFunction(A<?> obj) in A
。我的返回类型和参数类型都是A的子类。我不明白为什么我仍然会得到这个错误。
这个是我看到的一个解决方案,可以将A
改成类似A<T, ChildName>
的形式,然后使用ChildName
作为抽象函数的参数类型。是否有其他方法可以解决这个问题?
英文:
I have the classes
abstract class A<T> {
public abstract A<T> someFunction(A<?> obj);
}
public class B extends A<Integer>{
public B someFunction(B obj){...}
}
I get an error that says Class B must be declared abstract or must implement the abstract method someFunction(A<?> obj) in A
. My return type and parameter type are children of A. I don't understand why I am still getting this error.
This is one solution I see where I can change A
to something like A<T, ChildName>
and use ChildName
as the abstract function's parameter type. Is there a different way of doing this?
答案1
得分: 4
B.someFunction()
返回一个比 A.someFunction()
更派生的类是可以的。这仍然是相同的方法,覆盖有效。
然而,B.someFunction()
接受一个比 A.someFunction()
更派生的类作为参数是不可以的。当尝试这样做时,覆盖会失效。
可以这样考虑:某人可能有一个对 A
的引用,但实际上是 B
的实例。他们可能调用它并传递一个真正的 A
。然而,B.someFunction()
期望一个 B
的实例,它将尝试调用 A
中不存在的 B
的方法,这将无法工作。
英文:
It is okay for B.someFunction()
to return a class more derived than A.someFunction()
. It is still the same method, and the override works.
However, it is not okay for B.someFunction()
to accept a parameter of a class more derived than A.someFunction()
. When you try to do that, the override breaks.
Think of it this way: someone may have a reference to an A
which is in fact an instance of B
. They may invoke it passing it an actual A
. However, B.someFunction()
expects an instance of B
, and it will try to invoke methods of B
which do not exist in the A
that was passed. That would not work.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论