Java final keyword for variables

2019-02-05 23:26发布

How does the final keyword not make a variable immutable? Wikipedia says it doesn't.

6条回答
不美不萌又怎样
2楼-- · 2019-02-06 00:02

Read the rest of the Wikipedia article:

To illustrate that finality doesn't guarantee immutability: suppose we replace the three position variables with a single one: public final Position pos; where pos is an object with three properties pos.x, pos.y and pos.z. Then pos cannot be assigned to, but the three properties can, unless they are final themselves.

查看更多
手持菜刀,她持情操
3楼-- · 2019-02-06 00:05

Although it's not recommended, Java allows final variables to be modified using reflection.

查看更多
爷、活的狠高调
4楼-- · 2019-02-06 00:06

because if a reference is final, you can still change things in the object to which the reference points. You just cant change the reference.

查看更多
男人必须洒脱
5楼-- · 2019-02-06 00:15

For primitives such as int, double, char etc it works more as you might expect.

private final int status = 10;
status = 20; // WONT COMPILE because status is final
查看更多
孤傲高冷的网名
6楼-- · 2019-02-06 00:17

In Java, the term final refers to references while immutable refers to objects. Assigning the final modifier to a reference means it cannot change to point to another object, but the object itself can be modified if it is mutable.

For example:

final ArrayList<String> arr = new ArrayList<String>();
arr.add("hello"); // OK, the object to which arr points is mutated
arr = null; // Not OK, the reference is final and cannot be reassigned to

As the Wikipedia article mentions, if you are coming from C++, you must dissociate the concept of const into final and immutable.

查看更多
一夜七次
7楼-- · 2019-02-06 00:20

Suppose you have declared that myList is final. You can still add new items to myList, so its state is NOT immutable. What you can't do, because of the final keyword, is to change myList to refer to a different list.

查看更多
登录 后发表回答