我是第一年通过Java学习OOP的学生 我试图理解泛型类型,在下面的例子中,我认为disguisedAs()返回指向对象实例的指针。事实并非如此 为什么我的代码不能正常工作?如何编译和运行呢? 提前谢谢!
public class GenericTest {
public static void main(String[] args) {
Animal tux = new Penguin();
DisguisedPerson<Animal> dave = new DisguisedPerson<Animal>(tux, "Dave");
dave.disguisedAs().call();
dave.reveal();
}
}
interface Disguised <T> {
T disguisedAs();
}
class Person {
String name;
Person(String name) {
this.name = name;
}
}
class DisguisedPerson<U> extends Person implements Disguised<U> {
U resembles;
DisguisedPerson(U costume, String name) {
super(name);
resembles = costume;
}
public U disguisedAs() {
return resembles;
}
void reveal() {
System.out.println(name + " was dressed up as a " + disguisedAs().species); // returns error: cannot find symbol!
}
}
abstract class Animal {
String species;
String call;
Animal(String c) {
species = this.getClass().getName();
this.call = c;
}
void call() {
System.out.println(this.call + "! ImA " + this.species);
}
}
class Penguin extends Animal {
Penguin() {
super("Pip");
}
}
答案 0 :(得分:2)
您的通话确实有效,因为U
可以是任何类型。
如果你制作U extends Animal,那么你可以使用Animal的字段/方法。
class DisguisedPerson<U extends Animal>
你必须这样做,否则你可以写
DisguisedPerson<Integer> dave = new DisguisedPerson<Integer>(1, "One");
答案 1 :(得分:1)
通用类DisguisedPerson<U>
不知道具体的泛型类型,具体而言,它不知道disguisedAs()
返回Animal
,它返回U
,但是你不知道这个U
是什么,它可能是Object
,显然Object
没有字段species
。
请记住,实际对象(在您的情况下确实是Animal
)仅在运行时“已知”,并且由于java有static typing,因此需要“知道”实际类型在编译时,它假定为Object
,除非您指定U extends ....
[在您的情况下为U extends Animal
]。