Initialize final variable before constructor in Java

后端 未结 9 1664
旧时难觅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:30

    Another possiblity is to initialize the field in an instance initializer blocK:

    public class Foo {
            final String bar;
    
            {
                    System.out.println("initializing bar");
                    bar = "created at " + System.currentTimeMillis();
            }
    
            public Foo() {
                    System.out.println("in constructor. bar=" + bar);
    
            }
    
            public static void main(String[] args) {
                    new Foo();
            }
    }
    
    0 讨论(0)
  • 2020-12-03 09:39
    private static final String name = getName();
    

    where getName() is a static function that gets you the name.

    0 讨论(0)
  • 2020-12-03 09:41

    In that case, you might as well make it static, too. And Java convention is to name such constants in ALL_CAPS.

    0 讨论(0)
提交回复
热议问题