What is the difference between a static and a non-static initialization code block

后端 未结 8 1804
萌比男神i
萌比男神i 2020-11-21 23:32

My question is about one particular usage of static keyword. It is possible to use static keyword to cover a code block within a class which does not belong to

8条回答
  •  -上瘾入骨i
    2020-11-22 00:35

    This is directly from http://www.programcreek.com/2011/10/java-class-instance-initializers/

    1. Execution Order

    Look at the following class, do you know which one gets executed first?

    public class Foo {
     
        //instance variable initializer
        String s = "abc";
     
        //constructor
        public Foo() {
            System.out.println("constructor called");
        }
     
        //static initializer
        static {
            System.out.println("static initializer called");
        }
     
        //instance initializer
        {
            System.out.println("instance initializer called");
        }
     
        public static void main(String[] args) {
            new Foo();
            new Foo();
        }
    }
    

    Output:

    static initializer called

    instance initializer called

    constructor called

    instance initializer called

    constructor called

    2. How do Java instance initializer work?

    The instance initializer above contains a println statement. To understand how it works, we can treat it as a variable assignment statement, e.g., b = 0. This can make it more obvious to understand.

    Instead of

    int b = 0, you could write

    int b;
    b = 0;
    

    Therefore, instance initializers and instance variable initializers are pretty much the same.

    3. When are instance initializers useful?

    The use of instance initializers are rare, but still it can be a useful alternative to instance variable initializers if:

    1. Initializer code must handle exceptions
    2. Perform calculations that can’t be expressed with an instance variable initializer.

    Of course, such code could be written in constructors. But if a class had multiple constructors, you would have to repeat the code in each constructor.

    With an instance initializer, you can just write the code once, and it will be executed no matter what constructor is used to create the object. (I guess this is just a concept, and it is not used often.)

    Another case in which instance initializers are useful is anonymous inner classes, which can’t declare any constructors at all. (Will this be a good place to place a logging function?)

    Thanks to Derhein.

    Also note that Anonymous classes that implement interfaces [1] have no constructors. Therefore instance initializers are needed to execute any kinds of expressions at construction time.

提交回复
热议问题