2017-02-28 232 views
-3

試圖從我的主類中調用類中的非靜態方法,創建主類的實例,並嘗試從非靜態方法運行該方法,但我仍然繼續獲取「非靜態方法不能從靜態上下文中引用「的錯誤。靜態靜態方法?

主類看起來像這樣;

public class WeatherController { 
    public static void main(String[] args) { 
     WeatherController mainController = new WeatherController(); 
     mainController.doStuff(); 
    } 

    public void doStuff() { 
     WeatherObservation newObservation = new WeatherObservation("Whyalla", "28-02-17", 38, 0, 1.3, 1); 
     WeatherObservation.printObservation(newObservation); 
     WeatherHistory newHistory = new WeatherHistory(); //Create new History Array 
     newHistory.arrayAdd(newObservation);    //Add the Observation to it. 

// These are the problem methods: 
     WeatherHistory.arrayPrint(newHistory); 
     WeatherObservation.setTemp(10); 
    } 
} // End Class 

doStuff應該是非靜態的,因爲我在mainController的一個實例上運行它,對吧?但它不能調用setTemp或arrayPrint。

+3

只是因爲你有'一個實例WeatherController'並不意味着你可以調用WeatherHistory'或'實例方法'WeatherObservation '沒有這些類的實例。 – shmosel

回答

3
WeatherHistory.arrayPrint(newHistory); 
WeatherObservation.setTemp(10); 

這些都是靜態的電話,與下面的代碼替換它們:

newHistory.arrayPrint(newHistory); 
newObservation.setTemp(10); 
+1

或者使它們成爲靜態的,因爲'WeatherObservation.printObservation()'大概是。看起來比'newHistory.arrayPrint(newHistory)'更有用。 – shmosel

+0

這樣做了,我想我明白了爲什麼,謝謝。 – DataThrust