試圖從我的主類中調用類中的非靜態方法,創建主類的實例,並嘗試從非靜態方法運行該方法,但我仍然繼續獲取「非靜態方法不能從靜態上下文中引用「的錯誤。靜態靜態方法?
主類看起來像這樣;
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。
只是因爲你有'一個實例WeatherController'並不意味着你可以調用WeatherHistory'或'實例方法'WeatherObservation '沒有這些類的實例。 – shmosel