Skip to content
Advertisement

Override generic method with more narrow parametrization

What I have:

I have a generic method which I want to override:

class A {}
class B extends A {}
class C {
  public <T extends A> void function(T param) { //will be overridden in heirs
    //...
  }
}

What I want:

There will be few classes that extend C-class and narrow parametrization. Example:

class D extends C {
  @Override
  public <T extends B> void function(T param) { //T extends B, not A!! Or even better if it can be only B-class, not heirs
    //...
  }
}

Question:

How can I achieve that?

EDIT:

Class C has many heirs: D, F, G, H… Each of those classes has the single method f(T param). And for each of those method I need T will be different heir of Z class in each case.

So I decide that I can set common API in C-class with help of generics. But if its impossible, maybe other way?

Advertisement

Answer

Parameterizing your classes could be a solution:

class C<T extends A> {

    public void function(T param) {
        // ...
    }

}

class D<T extends B> extends C<T> {

    @Override
    public void function(T param) {
        // ...
    }

}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement