非静态方法不能从静态上下文中引用 [英] non static method cannot be referenced from static context

查看:82
本文介绍了非静态方法不能从静态上下文中引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The code below occurs in the main class of a package I'm trying to create. It references objects and methods from a helper class called Journey. At the call of the journeyCost method in the line marked by stars I get a "non static method cannot be referenced from static context" error. This has confused me as I was under the impression that the Journey object "thisJourney", created in the second line, constitutes an instance of the class and thus means the context is not static. Thanks in advance, 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);
        }

    } 

推荐答案

该错误表示您正在尝试以静态方式调用非静态方法,例如以下方法:

The error means that you are trying to call a non static method in a static way, like maybe this one:

 Journey.journeyCost(thisJourney);

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

Is journeyCost() declared static? Don't you mean instead thisJourney.journeyCost()?

此外,您应该使用getter和setter来修改和访问您的成员变量,所以不要:

Plus you should use getters and setters to modify and access your member variables, so instead of:

Journey.dayCharge = ...

您应该拥有

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

(在这种情况下,setDayChargegetDayCharge必须为静态)

(setDayCharge and getDayCharge need to be static in this case)

这篇关于非静态方法不能从静态上下文中引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆