user5549921
user5549921

Reputation:

Inheriting child-specific method from parent

I don't know if this is at all possible, but I was thinking of something in Java:

If I have an abstract parent class, I can do this:

public ParentClass add(ParentClass a, ParentClass b);

If ParentClass then has a child and I want to override this method, the child class will still have a ParentClass add(ParentClass, ParentClass) method.

Is there a way to make the parent function derive itself to each child?
I don't know if I'm wording it right, but something like this:

// ParentClass.java
public ParentClass add(ParentClass a, ParentClass b);

// Foo.java
@Override // or an equivalent
public Foo add(Foo a, Foo b) {}

// Bar.java
@Override
public Bar add(Bar a, Bar b) {}

Notice how each child doesn't have a ParentClass add(...) function, but rather one for each of their own types instead?

Obviously I can just make these myself, but I want to be able to create overridable ones in parents. I've never seen this in practice before, so I doubt its existence. I just want to clarify with someone with a higher Java knowledge than me. Thanks.

In theory, which I guess no language has ever done, something like this:

public child add(child a, child b);
// where *child* is the type of the child inheriting the method

Upvotes: 2

Views: 109

Answers (2)

davidxxx
davidxxx

Reputation: 131356

In Java covariance of parameters of a method is not allowed.
This inherited method : public ParentClass add(ParentClass a, ParentClass b); is legal for all children as it will allow to specify any subclass of ParentClass as parameters.
It is more flexible.
Now, if you don't want this flexibility and you want to force a specific type for parameters in the inherited method, you should use a generics abstract class.

public abstract class ParentClass <T extends ParentClass <?>>{
    public abstract ParentClass<?> add(T a, T b);
}

And in child class you could write :

public class ChildClass extends ParentClass <ChildClass>{
    public ParentClass<?> add(ChildClass a, ChildClass b){
       ....
   }
}

Upvotes: 3

Yosef Weiner
Yosef Weiner

Reputation: 5751

Something like this could work with Generics:

public abstract class ParentClass<T extends ParentClass> {
    public abstract T add(T a, T b);
}

class Foo extends ParentClass<Foo> {
    @Override
    public Foo add(Foo a, Foo b) {
        return null;
    }
}

class Bar extends ParentClass<Bar> {
    @Override
    public Bar add(Bar a, Bar b) {
        return null;
    }
}

Upvotes: 1

Related Questions