Static Final Variable in Java [duplicate]

2019-02-02 20:09发布

问题:

Possible Duplicate:
private final static attribute vs private final attribute

What's the difference between declaring a variable as

static final int x = 5;

or

final int x = 5;

If I only want to the variable to be local, and constant (cannot be changed later)?

Thanks

回答1:

Just having final will have the intended effect.

Declaring static is making it a class variable, this would be accessed through the class name <ClassName>.x.



回答2:

Declaring the field as 'final' will ensure that the field is a constant and cannot change. The difference comes in the usage of 'static' keyword.

Declaring a field as static means that it is associated with the type and not with the instances. i.e. only one copy of the field will be present for all the objects and not individual copy for each object. Due to this, the static fields can be accessed through the class name.

As you can see, your requirement that the field should be constant is achieved in both cases (declaring the field as 'final' and as 'static final').

Similar question is private final static attribute vs private final attribute

Hope it helps



回答3:

In first statement you define variable, which common for all of the objects (class static field).

In the second statement you define variable, which belongs to each created object (a lot of copies).

In your case you should use the first one.



回答4:

For the primitive types, the 'final static' will be a proper declaration to declare a constant. A non-static final variable makes sense when it is a constant reference to an object. In this case each instance can contain its own reference, as shown in JLS 4.5.4.

See Pavel's response for the correct answer.