Java static final values replaced in code when compiling?

后端 未结 10 1306
死守一世寂寞
死守一世寂寞 2020-11-28 10:27

In java, say I have the following

==fileA.java==
class A
{  
    public static final int SIZE = 100;
}  

Then in another file I use this valu

10条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-28 11:30

    One thing should note is: static final value is known at compile time if the value is not known at compile time, compiler won't replaces the constant name everywhere in the code with its value.

      public class TestA {
          // public static final int value = 200;
          public static final int value = getValue();
          public static int getValue() {
            return 100;
          }
      }
    
    public class TestB {
        public static void main(String[] args) {
            System.out.println(TestA.value);
        }
    }
    

    first compile TestA and TestB, run TestB

    then change TestA.getValue() to return 200, compile TestA, run TestB, TestB will get the new value enter image description here

提交回复
热议问题