What is an initialization block?

后端 未结 10 1860
青春惊慌失措
青春惊慌失措 2020-11-22 03:42

We can put code in a constructor or a method or an initialization block. What is the use of initialization block? Is it necessary that every java program must have it?

10条回答
  •  情歌与酒
    2020-11-22 03:57

    Just to add to the excellent answers from @aioobe and @Biman Tripathy.

    A static initializer is the equivalent of a constructor in the static context. which is needed to setup the static environment. A instance initializer is best for anonymous inner classes.

    • It is also possible to have multiple initializer blocks in class
    • When we have multiple initializer blocks they are executed (actually copied to constructors by JVM) in the order they appear
    • Order of initializer blocks matters, but order of initializer blocks mixed with Constructors doesn't
    • Abstract classes can also have both static and instance initializer blocks.

    Code Demo -

    abstract class Aircraft {
    
        protected Integer seatCapacity;
    
        {   // Initial block 1, Before Constructor
            System.out.println("Executing: Initial Block 1");
        }
    
        Aircraft() {
            System.out.println("Executing: Aircraft constructor");
        }
    
        {   // Initial block 2, After Constructor
            System.out.println("Executing: Initial Block 2");
        }
    
    }
    
    class SupersonicAircraft extends Aircraft {
    
        {   // Initial block 3, Internalizing a instance variable
            seatCapacity = 300;
            System.out.println("Executing: Initial Block 3");
        }
    
        {   // Initial block 4
            System.out.println("Executing: Initial Block 4");
        }
    
        SupersonicAircraft() {
            System.out.println("Executing: SupersonicAircraft constructor");
        }
    }
    

    An instance creation of SupersonicAircraft will produce logs in below order

    Executing: Initial Block 1
    Executing: Initial Block 2
    Executing: Aircraft constructor
    Executing: Initial Block 3
    Executing: Initial Block 4
    Executing: SupersonicAircraft constructor
    Seat Capacity - 300
    

提交回复
热议问题