I have a class Car which has a class scope variable cost, i understand that this is a bad idea in practice, just trying to understand the effects of public scope class variables.
Will cost be accessible and modifiable by all objects of class Car, references by Car.cost, throughout all class loaders, or should i be aware of circumstances where multiple copies of Car.cost might exist? Will there be just one Car.cost in any given circumstance?
public class Car{
public static int cost;
public Car(int cost){
cost = cost;
}
}
public static void main(String args[]){
Car car = new Car(2);
}
By specifying the
costfield asstaticyou are saying that there will only ever be a single, shared instance of that variable regardless of how many Car classes are created (within a process.) And yes, any of those instances will be able to modify that single, shared field and since you made it public, so will any other client code that has access to theCarclass. (Other processes that might use the same classes will have their own copies of static class members and will not be able to “see” across the process boundaries.)Semantically speaking, and if I infer the meaning for Car and cost correctly, you do not want to use a static UNLESS you want ALL your cars to cost the same. In the real world cost of a car is a highly variable attribute even between the same model of the same make of a car due to trim, options etc.