sidgate
sidgate

Reputation: 15254

Overriding method with generics parameter

We have a method in class that takes generic parameter

public class XYZ {
     public <T extends Animal> someMethod(T animal){}
}

I want to override this method in the subclass with specific type, but don't know how. How to fix this?

public class ABC extends XYZ{
  @Override
  public Cat someMethod(Cat animal){}  // error
}

Upvotes: 0

Views: 108

Answers (1)

assylias
assylias

Reputation: 328855

One possible solution would be to make your XYZ class generic:

public class XYZ<T extends Animal> {

    public void someMethod(T animal) {
    }
}

And declare your ABC class to be specific to cats:

public class ABC extends XYZ<Cat> {
}

Now you can write:

ABC cats = new ABC();
cats.someMethod(new Cat()); //ok
cats.someMethod(new Dog()); //does not compile

Upvotes: 5

Related Questions