非静态方法不能从静态上下文中引用
下面的代码出现在我尝试创建的包的主类中。它引用一个名为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);
}
}
的错误意味着您正试图调用非静态方法以静态方式,就像也许这一个:
Journey.journeyCost(thisJourney);
是journeyCost()
声明为static?你的意思不是指thisJourney.journeyCost()
?
另外,你应该使用getter和setter方法来修改和访问您的成员变量,所以不是:
Journey.dayCharge = ...
你应该有
Journey.setDayCharge(Journey.getDayCharge() + thisJourney.getCostOfJourney());
(setDayCharge
和getDayCharge
需要在这个静态案例)
也许方法journeyCost(Journey之旅)应该是静态的?
您使用Journey.someMethod()的时候,someMethod是一个静态方法。 “旅程”处于静态环境中。 thisJourney处于非静态环境中,因为它是一个实例。因此,你应该使用
thisJourney.updateCurrentCharges(date);
变化
Journey.journeyCost(....)
到
thisJourny.journyCost(...........)
您journyCost是Journy CLSS的非静态方法,所以你必须调用此方法通过它的对象是thisJourny
使用类名称,您只能访问静态成员或可以调用静态方法该类。
所有这些行都需要更改。除非你真的想改变这一切的未来之旅的费用与最后三行(这将是假设那些都是静态值)
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;
收费虽然即使该电荷值应该是某个常数试试这个。你真的不应该混合同一类型的静态类和实例类,同时交换它们的用途。
方法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);
请发表(再次...)整个堆栈跟踪:P – m0skit0 2012-04-10 13:34:56