Initialize final variable before constructor in Java

后端 未结 9 1736
旧时难觅i
旧时难觅i 2020-12-03 09:00

Is there a solution to use a final variable in a Java constructor? The problem is that if I initialize a final field like:

private final String name = \"a na         


        
9条回答
  •  悲&欢浪女
    2020-12-03 09:15

    I do not really understand your question. That

    public class Test3 {
        private final String test = "test123";
    
        public Test3() {
            System.out.println("Test = "+test);
        }
    
        public static void main(String[] args) {
            Test3 t = new Test3();
        }
    }
    

    executes as follows:

    $ javac Test3.java && java Test3
    Test = test123
    

提交回复
热议问题