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

前端 未结 18 2553
醉酒成梦
醉酒成梦 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:31

    I thought of writing an updated and in depth answer here.

    final keyword can be used in several places.

    1. classes

    A final class means that no other class can extend that final class. When Java Run Time (JRE) knows an object reference is in type of a final class (say F), it knows that the value of that reference can only be in type of F.

    Ex:

    F myF;
    myF = new F();    //ok
    myF = someOther;  //someOther cannot be in type of a child class of F.
                      //because F cannot be extended.
    

    So when it executes any method of that object, that method doesn't need to be resolved at run time using a virtual table. i.e. run-time polymorphism cannot be applied. So the run time doesn't bother about that. Which means it saves processing time, which will improve performance.

    1. methods

    A final method of any class means that any child class extending that class cannot override that final method(s). So the run time behavior in this scenario is also quite same with the previous behavior I mentioned for classes.

    1. fields, local variables, method parameters

    If one specified any kind of above as final, it means that the value is already finalized, so the value cannot be changed.

    Ex:

    For fields, local parameters

    final FinalClass fc = someFC; //need to assign straight away. otherwise compile error.
    final FinalClass fc; //compile error, need assignment (initialization inside a constructor Ok, constructor can be called only once)
    final FinalClass fc = new FinalClass(); //ok
    fc = someOtherFC; //compile error
    fc.someMethod(); //no problem
    someOtherFC.someMethod(); //no problem
    

    For method parameters

    void someMethod(final String s){
        s = someOtherString; //compile error
    }
    

    This simply means that value of the final reference value cannot be changed. i.e. only one initialization is allowed. In this scenario, in run time, since JRE knows that values cannot be changed, it loads all these finalized values (of final references) into L1 cache. Because it doesn't need to load back again and again from main memory. Otherwise it loads to L2 cache and does time to time loading from main memory. So it is also a performance improvement.

    So in all above 3 scenarios, when we have not specified the final keyword in places we can use, we don't need to worry, compiler optimizations will do that for us. There are also lots of other things that compiler optimizations do for us. :)

提交回复
热议问题