I'm reading Java tutorials from the begining and I have a question about static
keyword on fields or variables. As Java
said here:
Class Variables (Static Fields)
A class variable is any field declared with the static modifier; this tells the compiler that there is exactly one copy of this variable in existence, regardless of how many times the class has been instantiated. A field defining the number of gears for a particular kind of bicycle could be marked as static since conceptually the same number of gears will apply to all instances.
With that, I guess that if you have an object (in this case, an instance of the class Bicycle
) and a field inside of it that its static
then, independently of if you are refearing to bicycle1
or bicycle2
, the field that its static will have the same value. Am I wrong or I understand it well?
I mean, if I have:
Bicycle bicycle1 = new Bicycle();
Bicycle bicycle2 = new Bicycle();
and in the class Bicycle
I have a static
field like:
class Bicycle{
static int gears;
//Methods to set and get gears
}
And in the bicycle1
I set the value of gears to seven:
bicycle1.setGears(7);
then if I try to get the value of gears in bicycle2
I should get the same value as I set on bicycle1
, right?
System.out.println(bicycle2.getGears()); //7
Well, here is where I have the doubt because as Java
said in the quote that I put above:
this tells the compiler that there is exactly one copy of this variable in existence
Where is this copy stored? How the objects access to that copy? When is this copy created?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…