2017-02-28 229 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