2013-10-27 35 views

回答

2

我猜你用這樣的代碼。

public class TestClass { 

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

public void doSth() { 

} 

您不能從主類調用非靜態方法。 如果你想從你的主類調用非靜態方法,例如你的類是這樣的:

TestClass test = new TestClass(); 
test.doSth(); 

並調用該方法。

1

你不能從一個靜態方法中調用一個非靜態方法而沒有實例化這個類。如果你想在不創建主類的新實例(一個新對象)的情況下調用另一個方法,那麼你也必須爲另一個方法使用static關鍵字。

package maintestjava; 

    public class Test { 

     // static main method - this is the entry point 
     public static void main(String[] args) 
     { 
      System.out.println(Test.addition(10, 10)); 
     } 

     // static method - can be called without instantiation 
     public static int addition(int i, int j) 
     { 
     return i + j; 
     } 
    } 

如果你想調用非靜態方法,你必須instatiate類,這種方式創建一個新的實例,這個類的一個對象:

package maintestjava; 

public class Test { 

    // static main method - this is the entry point 
    public static void main(String[] args) 
    { 
     Test instance = new Test(); 
     System.out.println(instance.addition(10, 10)); 
    } 

    // public method - can be called with instantiation on a created object 
    public int addition(int i, int j) 
    { 
    return i + j; 
    } 
} 

查看更多: Static keyword on wikipedia Static on about.com

1

主要方法是一個靜態方法,所以它不存在於一個對象內部。

要調用非靜態方法(在其定義前沒有「static」關鍵字的方法),您需要使用new創建該類的對象。

您可以使其他方法靜態,這將解決眼前的問題。但它可能會或可能不是很好的面向對象的設計來做到這一點。這取決於你想要做什麼。

2

您的方法沒有使用關鍵字'static'來定義我的想法。 您不能在靜態上下文(如主方法)中調用非靜態方法。

Java Object Oriented Programming

3

靜態方法意味着你不需要調用該方法上的一個實例(對象)。非靜態(實例)方法要求您在實例上調用它。所以想想吧:如果我有一個方法changeThisItemToTheColorBlue()我試圖從主方法運行它,它會改變什麼樣的實例?它不知道。您可以在實例上運行實例方法,如someItem。 changeThisItemToTheColorBlue()。在http://en.wikipedia.org/wiki/Method_(computer_programming)#Static_methods

的唯一方法

更多信息調用從一個靜態方法的非靜態方法是讓含有非靜態方法的類的一個實例。根據定義,非靜態方法是一個被稱爲ON的某個類的實例,而靜態方法屬於該類本身。

是當你嘗試調用String類的非靜態方法startsWith沒有一個實例,如:

String.startsWith("Hello"); 

你需要的是有一個實例,然後調用非靜態方法:

String greeting = new String("Hello World"); 
greeting.startsWith("Hello"); // returns true 

所以你需要創建和實例來調用它。

而且約爲靜態方法更清晰,你可以參考

https://softwareengineering.stackexchange.com/questions/211137/why-can-static-methods-only-use-static-data

相關問題