简体   繁体   中英

Priority in java

Can any one explain me how this output come

class Class
{    
    {   
        System.out.println("Instance Initializer block");   
    }

    Class()
    {
       System.out.println("Default Constructor");
    }

    static
    {
        System.out.println("Static Block");
    }

    public static void main(String[] Args) 
    {
        new Class();
        System.out.println("Hello world");
    }
}

output:

Static Block
Instance Initializer Block
Default Constructor
Hello World

The static initializer block is executed first, when the class is initialized, printing "Static Block" .

When the instance is created ( new Class() ), first the instance initializer block is executed (printing "Instance Initializer Block" ) and then the constructor (printing "Default Constructor" ).

Finally the println statement of the main method is executed, printing "Hello World" .

The sequence is as follows

  1. Static initialization block is being ran when JVM (class loader ) loads Class ( static block is called irrespective of instance creation )
  2. when you try to create the instance 2.1 init block is called 2.2 then the constructor.
  3. At last your print statement

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM