Static Final Variable in Java [duplicate]

2019-02-02 20:13发布

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

4条回答
2楼-- · 2019-02-02 20:44

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.

查看更多
SAY GOODBYE
3楼-- · 2019-02-02 20:53

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.

查看更多
手持菜刀,她持情操
4楼-- · 2019-02-02 20:58

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

查看更多
走好不送
5楼-- · 2019-02-02 20:59

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.

查看更多
登录 后发表回答