有没有人能告诉我如何在函数“getDirectHair()”中编写返回值?
我想创建一个类似于Human类中的快捷方式的方法,直接返回良好类型的Hair类(下面命名为“h.getDirectHair()”),而不是使用“h.getPerson()。getHair()”。
我想使用类型<?>人的<?>在人类中宣布。
package test;
public class Test {
public static void main(String[] args) {
Human<Bob> h = new Human<Bob>();
Blond blond = h.getPerson().getHair(); // no cast needed, because Human<Bob> is blond
//how to do if I want to use directly this :
blond = (!!!) h.getDirectHair(); //need cast !! Blond or Brown ?
}
}
class Human<T extends Person<?>>{
private T person = null;
public T getPerson() {
return person;
}
public /* <?> */ Object getDirectHair(){
// => I want to return the type <?> of Person<?>
// instead of Object, how to ??
return person.getHair();
}
}
class Person<T extends Hair> {
T hair;
public Person(T hairr) {
hair = hairr;
}
public T getHair() {
return hair;
}
}
class Bob extends Person<Blond> {
public Bob(Blond bean) {
super(bean);
}
public Blond getHair() {
return super.getHair();
}
}
class Barack extends Person<Brown> {
public Barack(Brown bean) {
super(bean);
}
public Brown getHair() {
return super.getHair();
}
}
class Hair {
}
class Blond extends Hair {
}
class Brown extends Hair {
}
非常感谢和最诚挚的问候,
大卫。
答案 0 :(得分:4)
以下是解决问题的方法:
public class Test {
public static void main(String[] args) {
Human<Blond, Bob> h = new Human<Blond, Bob>();
Blond blond = h.getPerson().getHair();
blond = h.getDirectHair();
}
}
class Human<H extends Hair, T extends Person<H>>{
private T person = null;
public T getPerson() {
return person;
}
public H getDirectHair(){
return person.getHair();
}
}