I have read this sentence in a book but I didn't understand it:
A field that is both static and final has only one piece of storage that cannot be changed.
Can anyone explain it for me?
I have read this sentence in a book but I didn't understand it:
A field that is both static and final has only one piece of storage that cannot be changed.
Can anyone explain it for me?
A static
variable is common for all instances of the class. A final
variable can not change after it has been set the first time.
So a static final
variable in Java is common for all instances of the class, and it can not be changed after it has been set the first time.
class Car {
static final int numberOfWheels = 4;
Color color;
public Car(Color color) {
this.color = color;
}
}
Now these cars have one variable color
each, but they share the variable numberOfWheels
and it can not be changed.
Car redCar = new Car(Red);
Car blueCar = new Car(Blue);
See the section 'Constants' for an explanation on this page:
http://download.oracle.com/javase/tutorial/java/javaOO/classvars.html
The source of your confusion may be that the word "static" in english and it's meaning in Java are only loosely related.
A variable defined in a class Cat in the "normal" way can be referred to as an instance variable.
class Cat {
int weight;
}
Each time you create a new object of type Cat, you create a new copy of the variable 'weight'. If you create 10 objects of type Cat, each one has it's own copy of the weight variable.
A 'static' variable can be thought of as a class level variable, as opposed to an instance variable. A static variable has only one copy and belongs to the class Cat itself, rather than there being one copy for each object of type Cat.
class Cat {
static String speciesName;
int weight;
}
Here, no matter how many objects of type Cat we create, there is only one copy of speciesName.
If the static variable is also 'final,' than this one copy of the variable is the only piece of storage that cannot be changed. If the variable 'weight' were final in the above example, there would be 10 pieces of storage which could not be changed -- one for each object of type Cat that we had created.