Skotarcz
Skotarcz

Reputation: 11

Multiple seperate objects constructed from same class

Beginner java programmer

I created a class Car

public class Car {

  private static final double MILES_PER_YEAR = 20000;
  private static final double GAS_PRICE =  2.50;

  private static double pricePerYear;
  private static double totalPrice;

  public Car(double initialPrice, double milesPerGallon) {
    pricePerYear = (MILES_PER_YEAR / milesPerGallon);
    totalPrice = initialPrice;
}

Then in my main function I construct two Car objects

Car civic = new Car(22000, 35.5);
Car prius = new Car(27135, 55.5);

However, when I check attributes of these objects with civic.getTotalPrice() and prius.getTotalPrice() they're always the same. The second object contruction always overrides the first and when I construct them like I did above ^^ and get both prices, they both return 27135. This happens the same way vice versa if I define them like this

Car prius = new Car(27135, 55.5);    
Car civic = new Car(22000, 35.5);

For the segment above, the return for both civic.getTotalPrice() and prius.getTotalPrice() comes out as 22000

I think the issue has something to do with keywords like public, private, static, void, final, etc. as I do not full yunderstand what they mean yes, but I'm confused as to why the code still runs if it is a keyword problem like that.

My main goal is to compare the seperate objects' attributes and modify them individually if that helps anyone understand where I was going with this.

Upvotes: 1

Views: 56

Answers (1)

Konrad Rudolph
Konrad Rudolph

Reputation: 545528

Make the member variables non-static:

public class Car {
  private static final double MILES_PER_YEAR = 20000;
  private static final double GAS_PRICE =  2.50;

  private double pricePerYear;
  private double totalPrice;

  public Car(double initialPrice, double milesPerGallon) {
    pricePerYear = (MILES_PER_YEAR / milesPerGallon);
    totalPrice = initialPrice;
  }
}

static specifically means that members don’t belong to one specific instance and are instead shared by all of them. This makes sense for values such as MILES_PER_YEAR and GAS_PRICE: these are always the same, regardless of what car you define.

Upvotes: 1

Related Questions