我是第一年通過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