Search code examples
javainheritanceabstract-class

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){...}
}

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?


Solution

  • 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.