The difference between structural code block, static code block and local code block in java

class StaticCode{
    int age;
    // static code block
    static{
        System.out.print("static ");
    }
    //construct code block
    {
        System.out.print("55 ");
    }    
    // Constructor
    StaticCode(int age){
        this.age=age;
        System.out.print(age+",");
    }
    void show(){
    // local code block
        {
            int age=30;
        }
        System.out.print("show:"+age+",");
    }
}
static class StaticCodeDemo{
    public static void main(String[] args){
        StaticCode p1=new StaticCode(20);
        p1.show();
        StaticCode p2=new StaticCode(20);
    }
}

// The execution result is: static 55 20, show: 20, 55 20,

 

// Analysis: 
// 1. Execute the StaticCode class first, so static
// 2. Create the p1 object, execute the construction code block, 55
// 3. Execute the constructor initialization, 20
// 4. Execute p1.show() ,show:20
// 5. Create p2 object, execute construction code block, 55
// 6. Execute constructor initialization, 20

// Summary: static code blocks are loaded only once as the class is loaded. The role is to initialize the class.
// Construct a code block that can initialize all objects. It is called several times to create a few objects, which is to perform general initialization for the objects.
// The constructor is to initialize the corresponding object.
// The local code block limits the life cycle of the variables in the function, age=30 local code is executed. automatically released.

 

Reprinted from: http://www.cnblogs.com/bigben223/p/7986179.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326163473&siteId=291194637