2011-09-03 85 views
1

我在下面的下面的代碼:的Java主 - 調用其他方法

public static void main(String args[]) 
{ 
start(); 
} 

我得到這個錯誤:非靜態方法start()方法不能從靜態上下文引用。

我該如何去做這件事?

+4

我建議初學者對Java的書嗎?或者至少閱讀Oracle提供的教程?你的問題表明你確實沒有牢牢掌握最基本的概念,要麼真的有幫助。 –

+0

你如何聲明你的開始()? –

回答

7

創建您的班級實例並調用該實例的start方法。 如果你的類名爲Foo然後用下面的代碼在你main方法:

Foo f = new Foo(); 
    f.start(); 

此外,請方法start靜態的,通過它聲明爲靜態的。

4

希望這可以幫助你..

public class testProgarm { 

    private static void start() { 
     System.out.println("Test"); 
    } 

    public static void main(String[] args) { 
     start(); 
    } 

} 

然而,這是不是一個好的做法,使一個方法是靜態的。您應該實例化對象並調用對象的方法。如果你的對象沒有狀態,或者你需要實現一個輔助方法,那麼static就是要走的路。

+1

「但是,使方法靜態不是一個好習慣。」這真的取決於。如果你沒有狀態,或者你需要實現一個輔助方法,static就是要走的路。 – helpermethod

+1

@Oliver:謝謝並同意,並在我的回答中提供您的答案 –

0

一種方法是在主方法內創建另一個類的實例,例如newClass並在其中調用start()方法。

newClass class = new newClass(); 
class.start(); 
0

Non static (& instance) methods, so you may need an instance of class to use.

public class TestClass { 

    public static void main(String[] args) { 
     start(); 

     TestClass tc = new TestClass(); 
     tc.start1() 
    } 

    // Static method 
    private static void start() { 
     System.out.println("start"); 
    } 

    // Non-static method 
    private void start1() { 
     System.out.println("start1"); 
    } 

} 
相關問題