下面的代码出现在我正在尝试创建的包的主类中。它从名为Journey的帮助程序类引用对象和方法。在星号标记的行中调用journeyCost
方法时,我得到“非静态方法无法从静态上下文引用”错误。这使我感到困惑,因为我认为在第二行创建的Journey对象“thisJourney”构成了类的实例,因此意味着上下文不是静态的。谢谢,Seany。
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);
}
}
答案 0 :(得分:5)
错误意味着您试图以静态方式调用非静态方法,就像这样:
Journey.journeyCost(thisJourney);
journeyCost()
是否已声明为静态?你不是指thisJourney.journeyCost()
?
另外,您应该使用getter和setter来修改和访问您的成员变量,而不是:
Journey.dayCharge = ...
你应该
Journey.setDayCharge(Journey.getDayCharge() + thisJourney.getCostOfJourney());
(setDayCharge
和getDayCharge
在这种情况下需要是静态的)
答案 1 :(得分:3)
更改
Journey.journeyCost(....)
到
thisJourny.journyCost(...........)
您的 journyCost 是 Journy clss的非静态方法,因此您必须通过其 thisJourny <的对象调用此方法/ p>
使用班级名称,您只能访问静态成员,或者可以调用该班级的静态方法。
答案 2 :(得分: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;
尽管电荷值应该是一些常数。你真的不应该混合使用相同类型的静态类和实例类,同时交换它们的用途。
答案 3 :(得分:1)
也许方法journeyCost(Journey旅程)应该是静态的?
答案 4 :(得分:1)
Whenener你使用Journey.someMethod(),someMethod是一个静态方法。 “旅程”处于静态背景中。 thisJourney在非静态上下文中,因为它是一个实例。因此,您应该使用
thisJourney.updateCurrentCharges(date);
答案 5 :(得分: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);