Declaring variable final and static

前端 未结 2 1910
自闭症患者
自闭症患者 2021-02-18 14:31

This comment was made in a code review and the person who made it is no longer on our team.

Any type that must be resolved by the classloader at runtime

2条回答
  •  面向向阳花
    2021-02-18 14:49

    The line of code is perfectly fine, and there is no real problem because the variable is final and static.

    Maybe the person who made that comment was confused by the following.

    In Java, when you create a public final static variable of type int (for example; it also works with some other types), then the compiler might, in places where you use that variable, substitute the actual constant value instead of a reference to the variable. For example, suppose you have the following:

    class A {
        public final static int VALUE = 3;
    }
    
    public class B {
        public static void main(String[] args) {
            System.out.println(A.VALUE);
        }
    }
    

    When you compile and run this, it will obviously print 3.

    Now suppose that you change class A and set VALUE = 4. You would expect that if you recompile class A and then run class B (without recompiling class B), you would see 4. But what happens is that you will still see 3. That is because the A.VALUE in class B was replaced by the actual constant value 3 when you compiled class B.

    This is an optimization that the Java compiler does for constants.

    As you can see this can cause problems, if you have such constants in the public API of your classes. Users of your code will have to recompile their code if you change the value of such constants.

    But in the code you posted in your question this is not a problem, because the variable is private.

    More details:

    Java Language Specification 13.4.9

提交回复
热议问题