-2

Here is my problem. When I use addCar(carobject), it says I'm making a static reference to a non-static method. How do I call the method in the main method? I want to be able to call the method addcar() with my object in the parenthesis. It appears to me as if it should work.

    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());
        }
    }
}
Cflo
  • 45
  • 1
  • 4
  • _It appears to me as if it should work_ Why? – Sotirios Delimanolis Jan 29 '15 at 22:15
  • 2
    It's OK to not understand this concept yet as you're new to Java, but we'd all be much better off if you'd search for it first before asking. Please use the search capabilities of this site, such as shown [here](http://stackoverflow.com/search?q=%5Bjava%5D+static+reference+nonstatic+method) before re-asking a question that gets asked quite often. – Hovercraft Full Of Eels Jan 29 '15 at 22:18

1 Answers1

0

This is because your are calling addCar in your main method which is static addCar is not.

If you want to call a method from your main, then you have to declare this method static.

However, a better approach would be to instantiate a constructor in your main and simply call the method from that constructor. Static is evil.

Jean-François Savard
  • 20,626
  • 7
  • 49
  • 76