如何使用有界类型参数扩展泛型类 [英] How to extend a generic class with bounded typed parameter
问题描述
我正在尝试将具有受限类型参数的泛型类扩展为另一个具有类型参数的泛型类,该泛型类遵循超级泛型的类型化参数。
I am trying to extend a Generic class with bounded typed parameter with another generic class with typed parameter which follows the super generic's typed parameter.
具有上限类型参数的超级泛型
Super Generic with upper bounded type parameter
public abstract class Cage<T extends Animal> {
protected Set<T> cage = new HashSet<T>();
public abstract void add(T animal);
public void showAnimals() {
System.out.println(cage);
}
}
我要使用特定的有界类型创建的泛型类例如Lion
Generic class I want to create with a specific bounded type e.g. Lion
我尝试了以下代码,但出现错误类型参数Lion隐藏了类型Lion 和语法错误令牌 extends,预期
I tried the below code but I am getting an error The type parameter Lion is hiding the type Lion and Syntax error on token "extends", , expected
对于LionCage类中的add()方法,我得到了错误 LionCage类型必须重写或实现超类型方法
For the add() method in LionCage class I am getting the error The method add(Lion) of type LionCage must override or implement a supertype method
LionCage
类表示笼子<狮子扩展动物> c>
public class LionCage<Lion extends Animal> extends Cage<T extends Animal> {
@Override
public void add(Lion l) {
cage.add(l);
}
}
我的动物类及其子类Lion ,大鼠等在Animal.java中定义。
My Animal class with its subclasses Lion, Rat, etc are defined in Animal.java
public class Animal {
public String toString() {
return getClass().getSimpleName();
}
}
class Rat extends Animal {}
class Lion extends Animal {}
由于我遇到了错误,我猜测我所遵循的方法可能不正确。在那种情况下,是否有任何标准方法可以在Java泛型中实现此方案?
Since I am getting the errors, I am guessing that the approach I am following may not be correct. In that case, is there any standard way of implementing this scenario in Java generics?
推荐答案
您的 LionCage
类不必是通用的,但是它必须在 extends
子句中传递一个具体的类型参数( Lion
):
Your LionCage
class doesn't have to be generic, but it has to pass a concrete type paramter (Lion
) in the extends
clause:
public class LionCage extends Cage<Lion> {
@Override
public void add(Lion l) {
cage.add(l);
}
}
这篇关于如何使用有界类型参数扩展泛型类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!