2012-03-14 114 views
2

我是第一年通過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"); 
    } 
} 
+0

對於具有真實代碼的真實特定問題+1,你已經嘗試了一些東西。太多的用戶最近都在嘗試「給我代碼」的問題:\ – amit 2012-03-14 17:19:14

回答

2

您的電話確實有效,因爲U可以是任何類型。

如果你讓U伸展動物,那麼你可以使用動物的領域/方法。

class DisguisedPerson<U extends Animal> 

你必須這樣做,或者你可以寫

DisguisedPerson<Integer> dave = new DisguisedPerson<Integer>(1, "One"); 
+0

是的! (如果我用23個驚歎號跟着那個,我會更精確地表達我的感受) 非常感謝你讓我明白這個關鍵點!現在我準備好完成我的任務。謝謝! – jollyroger 2012-03-14 16:59:14

1

泛型類DisguisedPerson<U>不知道具體的泛型類型,具體而言,它並不知道disguisedAs()返回一個Animal,它返回一個U,但你不知道這個U是什麼,它可能是一個Object,顯然Object沒有一個字段species

請記住,實際上你的實際對象Animal僅在運行時「已知」,並且由於java有static typing,它需要在編譯時「知道」實際類型,所以它假定一個Object,除非你指定U extends .... [你的情況U extends Animal]。

+0

謝謝你讓我完全清楚。明確指出我的語法含糊不清是有幫助的,所以我對問題有了充分的理解。 – jollyroger 2012-03-14 17:14:07

+0

@jollyroger:你很受歡迎,祝你好運! – amit 2012-03-14 17:17:45