Why must a final variable be initialized before constructor completes?

后端 未结 9 491
暖寄归人
暖寄归人 2020-12-01 03:38

Why must a final variable be initialized before constructor completes?

public class Ex
{
  final int q;
}

When I compile this code I get er

9条回答
  •  一生所求
    2020-12-01 03:56

    The final keyword applied to a field has one of two effects:

    • on a primitive, it prevents the value of the primitive from being changed (an int can't change value)
    • on an object, it prevents the "value of the variable", that is, the reference to the object, from being changed. That is to say that, if you have a final HashMap a, you will only be able to set it once, and you won't be able to do this.a=new HashMap(); again, but nothing keeps you from doing this.a.put("a","b"),s since that doesn't modify the reference, only the content of the object.

提交回复
热议问题