How does the “final” keyword in Java work? (I can still modify an object.)

前端 未结 18 2571
醉酒成梦
醉酒成梦 2020-11-22 03:08

In Java we use final keyword with variables to specify its values are not to be changed. But I see that you can change the value in the constructor / methods of

18条回答
  •  野性不改
    2020-11-22 03:18

    This is a very good interview question. Sometimes they might even ask you what is the difference between a final object and immutable object.

    1) When someone mentions a final object, it means that the reference cannot be changed, but its state(instance variables) can be changed.

    2) An immutable object is one whose state can not be changed, but its reference can be changed. Ex:

        String x = new String("abc"); 
        x = "BCG";
    

    ref variable x can be changed to point a different string, but value of "abc" cannot be changed.

    3) Instance variables(non static fields) are initialized when a constructor is called. So you can initialize values to you variables inside a constructor.

    4) "But i see that you can change the value in the constructor/methods of the class". -- You cannot change it inside a method.

    5) A static variable is initialized during class loading. So you cannot initialize inside a constructor, it has to be done even before it. So you need to assign values to a static variable during declaration itself.

提交回复
热议问题