-5

Every time I create an object of the class it returns the same value every time, even if the object is different with different values. How can I make sure that this doesn't happen?

class Something{
  protected String name;
  protected static double price; // need the value later

  public Something(String xName, double xPrice){
    name = xName;
    price = xPrice;
  }

  public String returnName(){
    return name;
  }

  public static returnPrice(){
    return price;
  }
}
Erwin Bolwidt
  • 30,799
  • 15
  • 56
  • 79
johnny
  • 5
  • 3
  • 3
    change `price` to be not static – Eran Feb 26 '18 at 12:58
  • [What is the exact meaning of static fields in Java?](https://stackoverflow.com/questions/797964/what-is-the-exact-meaning-of-static-fields-in-java) – haukex Feb 26 '18 at 13:01
  • Why did you make the field `price` and the method `returnPrice` to be **`static`** ? That's the problem, you shouldn't :- but why did you do it in the first place? – Erwin Bolwidt Feb 26 '18 at 14:59

1 Answers1

2

If you need the value of price as unique to object, you should not declare it as static. If you declare as static, it will be accessible within all objects of given class and it won't belong to object.

yılmaz
  • 1,818
  • 13
  • 15