如何将此静态引用修复为非静态方法?

时间:2015-01-29 22:14:27

标签: java static

这是我的问题。当我使用addCar(carobject)时,它说我正在对非静态方法进行静态引用。如何在main方法中调用该方法?我希望能够在括号中使用我的对象调用方法addcar()。在我看来好像它应该工作。

    package Lab2;
/*********************************************************************
//Race.java       
//
//Race class defines what the race object is
//and what it can do.
//********************************************************************
*/
public class Race {
    public double distance;
    public String raceType;
    public Car[] carsEntered = new Car[3];
    final int DEFAULTNUMBEROFCARS = 3;
    public static void main(String[] args) {
        int carCount = 0;
        String winner;

        Car myCar = new Car("Chase", 75);
        Car ProfCar = new Car("Prof. Harms", 85);
        Car JeffCar = new Car("Jeff Gordan", 100);
        addCar(myCar);

    }
    /**
     * Changes the distance of the race.
     */
    public void changeDistace(double newDistance) {
        distance = newDistance;
    }

    /**
     * Changes the Type of the race.
     */
    public void changeRaceType(String newRaceType) {
        raceType = newRaceType;
    }

    /**
     * Adds a new car to the Race.
     */
    public void addCar(Car newCar) {
        boolean carPlaced = false;
        for(int i=0; i<DEFAULTNUMBEROFCARS;i++) {
            if(carPlaced == false) {
                if(carsEntered[i] == null) {
                    carsEntered[i] = newCar;
                    carPlaced = true;
                }
            }

        }
    }
    public String getRaceType() {
        return raceType;
    }
    /**
     * Prints the cars in the race.
     */
    public void getCarsEntered() {
        for(int i=0;i<carsEntered.length; i++) {
            System.out.println("Owner: " + carsEntered[i].getOwner());
        }
    }
}

1 个答案:

答案 0 :(得分:0)

这是因为您在main方法中调用了addCar,而静态addCar则不是。

如果要从main调用方法,则必须将此方法声明为static。

但是,更好的方法是在main中实例化一个构造函数,然后从该构造函数中调用该方法。静是邪恶的。