Java泛型:实际类作为泛型参数

时间:2010-12-27 11:49:28

标签: java generics

我该怎么写而不是“TheClass”来使这项工作?或者是否有另一种方法(可能没有使用WithName和WithAge泛型)?

class Item {
 NeigborList<TheClass> neighbors;
}

class WithName extends Item { // here I want neighbors to be a NeighborList<WithName>
 String name;
 void someMethod() {
  System.out.println(neighbors.nearestTo(this).name);
 }
}

class WithAge extends Item { // here I want neighbors to be a NeighborList<WithAge>
 int age;
 void someOtherMethod() {
  System.out.println(neighbors.nearestTo(this).age);
 }
}

1 个答案:

答案 0 :(得分:4)

我想你想说这个

class Item <T> {
    NeigborList<T> neighbors;
}

class WithName extends Item<WithName> {
    ...
}