开发者

Java generics: actual class as a generic parameter

开发者 https://www.devze.com 2023-02-01 02:33 出处:网络
What do I write instead of \"TheClass\" to make this work? Or is there an alternative way to do it (possibly without making WithName and WithAge generic)?

What do I write instead of "TheClass" to make this work? Or is there an alternative way to do it (possibly without making WithName and WithAge generic)?

class Item {
 NeigborList<TheClass> neighbors;
}

class WithNam开发者_开发知识库e 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);
 }
}


I think you wanted to say this

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

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

精彩评论

暂无评论...
验证码 换一张
取 消