1

下面的代码出现在我试图创建的包的主类中。它从一个名为 Journey 的帮助器类中引用对象和方法。在星号标记的行中调用journeyCost方法时,出现“无法从静态上下文引用非静态方法”错误。这让我感到困惑,因为我的印象是在第二行中创建的 Journey 对象“thisJourney”构成了该类的一个实例,因此意味着上下文不是静态的。在此先感谢,西尼。

public boolean journey(int date, int time, int busNumber, int journeyType){
        Journey thisJourney = new Journey(date, time, busNumber, journeyType);

        if (thisJourney.isInSequence(date, time) == false)
        {
            return false;            
        }
        else
        {
            Journey.updateCurrentCharges(date);

            thisJourney.costOfJourney = Journey.journeyCost(thisJourney);***** 
            Journey.dayCharge = Journey.dayCharge + thisJourney.costOfJourney;
            Journey.weekCharge = Journey.weekCharge + thisJourney.costOfJourney;
            Journey.monthCharge = Journey.monthCharge + thisJourney.costOfJourney;

            Balance = Balance - thisJourney.costOfJourney;
            jArray.add(thisJourney);
        }

    } 
4

6 回答 6

5

该错误意味着您正在尝试以静态方式调用非静态方法,例如:

 Journey.journeyCost(thisJourney);

是否journeyCost()声明为静态?你不是说相反thisJourney.journeyCost()吗?

另外,您应该使用 getter 和 setter 来修改和访问您的成员变量,而不是:

Journey.dayCharge = ...

你应该有

Journey.setDayCharge(Journey.getDayCharge() + thisJourney.getCostOfJourney());

(在这种情况setDayChargegetDayCharge需要是静态的)

于 2012-04-10T13:34:26.883 回答
3

所有这些行都需要更改。除非您真的想用最后三行更改所有未来的旅程费用(假设这些是静态值)

thisJourney.costOfJourney = thisJourney.journeyCost();//dont know why you are passing the journey object to this method.
Journey.dayCharge = Journey.dayCharge + thisJourney.costOfJourney;
Journey.weekCharge = Journey.weekCharge + thisJourney.costOfJourney;
Journey.monthCharge = Journey.monthCharge + thisJourney.costOfJourney;

最后三行仍然需要工作,我不知道您为什么要尝试修改静态变量。如果您只想设置thisJourney

thisJourney.dayCharge = Journey.dayCharge + thisJourney.costOfJourney;
thisJourney.weekCharge = Journey.weekCharge + thisJourney.costOfJourney;
thisJourney.monthCharge = Journey.monthCharge + thisJourney.costOfJourney;

尽管即使如此,电荷值也应该是恒定的。您真的不应该混合使用相同类型的静态类和实例类,同时互换它们的用途。

于 2012-04-10T13:41:42.293 回答
3

改变

Journey.journeyCost(....)

thisJourny.journyCost(...........)

您的journyCost是Journy clss的非静态方法,因此您必须通过其对象thisJourny调用此方法

使用类名,您只能访问静态成员或调用该类的静态方法。

于 2012-04-10T13:35:48.803 回答
1

该方法journeyCost是非静态的;所以它是一个实例方法,它需要一个实例Journey来执行。该语句Journey.journeyCost(thisJourney);以静态方式调用方法,并且期望您的方法是类级方法(或静态)。

因此,您可以使您的journeyCost方法静态以使您的调用生效:

public static boolean journey(int date, int time, int busNumber, int journeyType)

或者尝试从适当的实例调用该方法:

Journey aJourneyInstance = new Journey();
thisJourney.costOfJourney = aJourneyInstance.journeyCost(thisJourney);
于 2012-04-10T13:41:51.470 回答
1

也许方法 JourneyCost(Journey Journey) 应该是静态的?

于 2012-04-10T13:35:33.847 回答
1

当你使用 Journey.someMethod() 时,someMethod 是一个静态方法。“旅程”是在静态上下文中。thisJourney 是在非静态上下文中,因为它是一个实例。因此,您应该使用

    thisJourney.updateCurrentCharges(date);
于 2012-04-10T13:35:40.363 回答