抽象方法在使用子类作为返回类型时不被视为已实现。

huangapple go评论123阅读模式
英文:

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&lt;T&gt; {

    public abstract A&lt;T&gt; someFunction(A&lt;?&gt; obj);
}

public class B extends A&lt;Integer&gt;{

    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&lt;?&gt; 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&lt;T, ChildName&gt; 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.

huangapple
  • 本文由 发表于 2023年5月17日 23:35:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/76273822.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定