Difference between the static initializer block and regular static initialization

后端 未结 8 1988
广开言路
广开言路 2021-01-05 12:12

As the title says, what exactly is the difference between

public static String myString = \"Hello World!\";

and

public stat         


        
8条回答
  •  -上瘾入骨i
    2021-01-05 12:25

    The static {...} block gives you the opportunity to do more than you would be able to do in the field declaration.

    For example, you can fill in some details of a map:

    private static final Map data = new HashMap();
    
    static {
        data.put("A", "Hello");
        data.put("B", "There");
        data.put("C", "You");
    }
    

    Sometimes you may also need to get data (from a file, database, etc) before you can instantiate:

    public class Foo {
        private static final Person person;
    
        static {
            InputStream personData = Foo.class.getResourceAsStream("something.txt");
            person = new Person(personData);
        }
        ...
    }
    

提交回复
热议问题