2013-07-04 152 views
1

我是一名本科大學生,試圖理解Java中的繼承。 docs.oracle站點說,類的所有成員都是繼承的,除了構造函數。這是有道理的。問題是我做了一個實驗,並沒有奏效。這裏是:Java,繼承和實例方法。爲什麼我的方法不會繼承?

public class One{ 
    public void outPrint(){ 
     System.out.println("Hello World!"); 
    }//end outPrint 
}//end One.java 

public class Two extends One{ 
    //empty 
}//end Two.java 

public class Three extends Two{ 
    public static void main(String[]args){ 
     outPrint(); 
    }//end main 
}//end Three.java 

當我運行三我得到:非靜態方法outPrint()不能從靜態上下文引用。這當然是因爲編譯器將outPrint()看作實例成員。如果我將關鍵字「static」添加到outPrint()方法頭部,那麼整個事情都可以正常工作。

這是我混亂的地方。它似乎不僅僅是不可繼承的構造函數,而且也是它的所有實例成員。任何人都可以解釋這對我更好一點嗎?有沒有涉及到使用「靜態」的工作?我嘗試了一些「超級」的試驗無濟於事。提前致謝!

+0

的簡單建議。也許你的老師建議(或強迫)你在每個括號的末尾加上註釋,但這對程序員來說是一種噪音。評論是針對可能不明確的事情,如解釋算法。如果您的代碼縮進(製表符,換行符等),那麼這些評論實際上是不必要的。 –

+0

這是推薦的,但它也幫助我閱讀代碼時,我必須調試。在這個例子中,它肯定顯得多餘,但是當我有幾百行代碼或更多的代碼時,我發現我可以更好地區分代碼塊。特別是當涉及到控制結構時。當我進入職業世界時,我相信我必須修改我的習慣!感謝您的建議! – gates3353

回答

5

您需要實例化要調用的對象。

例如

Three t = new Three(); 
t.outPrint(); 

你定義的main()方法是靜態的,並且不具有一個對象(One/Two/Three)的實例。它僅存在於特定的命名空間中。

注意,您可以證明Three是,一個One這樣的:

One t = new Three(); 
t.outPrint(); 

,如果你重寫outPrint()方法對每個子類,你可以看到哪些方法隨叫你如何實例化和/或者引用原始對象實例。

+0

不錯!我知道我喜歡在這裏發佈問題的原因!所以,澄清:我得到我的錯誤,因爲我試圖從靜態main()方法調用outPrint()?現在我認爲這很有道理!謝謝!快樂的第四! – gates3353

+0

沒問題。回覆。第四,我是英國人,所以我只等聖喬治節:-) –

+0

哈哈,諷刺!謝謝你的幫助! – gates3353

1

您正在嘗試調用不帶實例的非靜態方法。實例方法只能使用類的實例來調用。創建一個實例,會幫你調用該方法,像這樣:

Three threeInstance = new Three(); 
threeInstance.outPrint(); 
1

對於您需要的class Threeclass Twoclass One箱對象。

public class Three extends Two 
{ 
    public static void main(String[]args) 
    { 

       Two t= new Two();   
       t.outPrint(); 

    } 
} 
1

試試這個

public class Three extends Two{ 

    public static void main(String[]args){ 
     Three three = new Three(); 
     three.outPrint(); //outPrint() can only be called by an instance 
    }//end main 

}//end Three.java 

不能從即使是在同一個類中的靜態方法來訪問非靜態方法。你將不得不通過一個實例訪問它們。

然而,下面也有可能Three.java類中:

public class Three extends Two{ 

    public static void main(String[]args){ 
     Three three = new Three(); 
     three.printSomething("Hi"); 
     // this will output: 
     // Hi 
     // Hello World 
    }//end main 
    public void printSomething(text) { 
     System.out.println(text); 
     outPrint(); //implicit "this" which refers to this instance....it can be rewritten as this.outPrint(); 
    } 
}//end Three.java