开发者

final and static in Java

开发者 https://www.devze.com 2023-01-21 18:02 出处:网络
I have开发者_StackOverflow中文版 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.

I have开发者_StackOverflow中文版 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?


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.


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;
    }
}

Car redCar = new Car(Red);
Car blueCar = new Car(Blue);

Each car now has one individual and variable property color and they share the property numberOfWheels which can not be changed.


See the section 'Constants' for an explanation on this page:

http://download.oracle.com/javase/tutorial/java/javaOO/classvars.html


  • Final means cannot re-assign value to any variable
  • Static means only one copy of reference can be in whole in the class of all methods.
0

精彩评论

暂无评论...
验证码 换一张
取 消