Search code examples
javaarraysnew-operator

Last Object in Array Replacing All Other Objects


When I create this array, the last object that I am creating is replacing the previous two objects before it.

public class Main
{
   public static final int NUM_CARS = 3;
   private static Scanner scanner;
   
   public static void main(String[] args)
   {
      Car[] cars;
      cars = new Car[NUM_CARS];
      cars[0] = new Car( "Toyota Camry", 3400 );
      cars[1] = new Car( "Ford F-150", 5000 );
      cars[2] = new Car( "Honda Civic", 3000 );
      System.out.println( cars[0] );
      System.out.println( cars[1] );
      System.out.println( cars[2] );

This is supposed to print the make and model of each car, with its MPG. But it ends up printing the third object (the Civic), three times. Here is the constructor:

public class Car
{
   private static String model; // Car make and model (e.g. "BMW 328i)
   private static double mpg; // Car's miles per gallon
   private static double milesDriven; // The total miles driven (odometer)
   private static double fuelGallons; // The amount of fuel in the tank (in gallons)
   
   public Car( String carModel, int weight )
   {
      model = carModel;
      if ( weight > 4000 )
         mpg = 20.0;
      else
         mpg = 30.0;
      milesDriven = 7;
      fuelGallons = 15;
   }
   

I thought that the "new" wouldn't override each element in the array, but that doesn't seem to be the case.


Solution

  • All the fields in your Car class are declared as static. That means that these 4 fields are shared by all Car instances.

    Replace the beginning of the Car class with:

    public class Car
    {
       private String model; // Car make and model (e.g. "BMW 328i)
       private double mpg; // Car's miles per gallon
       private double milesDriven; // The total miles driven (odometer)
       private double fuelGallons; // The amount of fuel in the tank (in gallons)
    

    to fix your problem.