为什么我无法访问此方法?

时间:2013-12-20 23:21:51

标签: java class methods

package learnclass;

public class Car {

    public String manuName;
    public int engineCC;
    public float fuelammount;
    public float carWeight;

    public float presentAmountFuel(){

        return fuelammount;
    }


}

//////////////////////

package learnclass;

public class LearningClass {
    static private Car ourCar;
    public static void main(String[] args) {

        ourCar.

    }

}

我无法通过ourCar对象访问presentAmountFuel()方法。为什么会这样?

2 个答案:

答案 0 :(得分:2)

如果您的方法不是静态的,则必须先初始化对象,然后才能使用其方法。

尝试使用以下代码访问您的对象方法:

package learnclass;

public class LearningClass 
{
    static private Car ourCar;
    public static void main(String[] args) 
    {
        ourCar = new Car();   // Initialize your object before you can use its method presentAmountFuel()
        ourCar.presentAmountFuel();    
    }

}

答案 1 :(得分:2)

您需要实例化对象。

static private Car ourCar = new Car();