我是第一年通过Java学习OOP的学生。
我想了解泛型类型,在下面的示例中,我感觉disguisedAs()返回指向对象实例的指针。不是这种情况。
为什么我的代码不工作,我怎样才能让它编译和运行?
在此先感谢!从Java中的泛型类型访问对象变量
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");
}
}
对于具有真实代码的真实特定问题+1,你已经尝试了一些东西。太多的用户最近都在尝试“给我代码”的问题:\ – amit 2012-03-14 17:19:14