Why final instance class variable in Java?

后端 未结 11 739
南方客
南方客 2020-12-09 05:13

If instance variable is set final its value can not be changed like

public class Final {

    private final int b;

    Final(int b) {
        this.b = b; 
         


        
11条回答
  •  旧巷少年郎
    2020-12-09 05:29

    In "C/C++" terms:

    Thing * a;
    Thing * const b;
    Thing const * c;
    Thing const * const d;
    

    The "final" in Java is closest to "b". "b" is a constant pointer to a Thing. "b" cannot be changed to point to a different Thing, but the Thing itself may be changed.

    Java doesn't have a representation for "c" and "d". "c" is a pointer to a constant Thing. "c" may point to other Things, but the Things it points to cannot be changed (at least, not through "c" itself)

    "d" combines "b" and "c": "d" is a constant pointer to a constant Thing.

    Oh, and "a" of course is just nothing special.

    Hm...In Java, not everything is an object so the rules are a little different.

    final int f = 9;
    

    Which, in C is much like

    int const f = 9;
    

    Which means you cannot change "f" or its integer value.

    NOTE:

    int const f;
    const int g;
    

    both mean the same thing, but "f" IMHO has clearer meaning. "g" is unfortunately very common.

提交回复
热议问题