静态代码块、非静态代码块 区别以及用途

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package extendinittest;
class Leaf{
    static {
        System.out.println("leaf static init");
    }
    {
        System.out.println("Leaf no static init");
    }
    Leaf(){
    System.out.println("leaf");
    }
}
class root{
    root(){ 
        System.out.println("root");
    }
}
class midClass extends root {
    static {
        System.out.println("mid calss static init");
    }
    midClass(){
        System.out.println("midClass");
    }
    {
        System.out.println("midclass no static init");
    }
}

/**
 *
 * @author thinkpad
 */
public class ExtendInitTest extends midClass {
    private Leaf l = new Leaf();
    ExtendInitTest(){
        System.out.println("ExtendInitTest");
    }
    static
    {
        System.out.println("static init");
    }
    {
        System.out.println("no static init");
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        new ExtendInitTest();
    }
    
}

输出结果:

mid calss static init
static init
root
midclass no static init
midClass
leaf
no static init
ExtendInitTest

你可能感兴趣的:(Java)