简体   繁体   中英

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
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM