java中静态块、main方法、构造块、构造方法的执行顺序复习

来源:互联网 发布:linux 显示行号的命令 编辑:程序博客网 时间:2024/06/05 13:48

写此文的目的是复习java中静态块、main方法、构造块、构造方法的执行顺序,直接运行下面的代码即可一目了然,不再多说。

/** * 运行父类main方法各个块作用域的执行顺序: * static块(且仅仅执行一次) -> main方法 -> 构造块 -> 构造方法 */public class Parent {    private int age = 0;    private String name = null;    private static String company = null;    static {        System.out.println("Parent static block runing");        company = "parent-ahik";    }    {        System.out.println("Parent constructor block runing");        this.name = "parent";    }    public Parent() {        System.out.println("Parent construct method Parent() runing");        this.age = 28;    }    public Parent(int age) {        System.out.println("Parent construct method Parent(int age) runing");        this.age = age;    }    @Override    public String toString() {        return "Parent{" +                "age=" + age +                ", name='" + name + '\'' +                ", company= '" + company + "' " +                '}';    }    public static void main(String... args) {        System.out.println("Parent main runing");        Parent p1 = new Parent();        System.out.println(p1);        Parent p2 = new Parent(33);        System.out.println(p2);        {            int i = 100;            System.out.println(i);        }        int i = 99;        System.out.println(i);    }}///////////////////////////////////////////////////////////////** * 运行子类main方法各个块作用域的执行顺序: * 父类static块(且仅仅执行一次)-> * 子类static块且仅仅执行一次) -> * 子类 main方法 -> * 父类构造块 -> * 父类构造构造方法 -> * 子类构造块 -> * 子类构造方法 */public class Child extends Parent {    private int age = 0;    private String name = null;    private static String company = null;    static {        System.out.println("Child static block runing");        company = "child-ahik";    }    {        this.name = "Child";        System.out.println("Child construct block start runing");    }    public Child() {        super(66);        this.age = 99;        System.out.println("Child construct method Child() runing");    }    public Child(int age) {        super(77);        this.age = age;        System.out.println("Child construct method Child(int age) runing");    }    public static void main(String... args) {        System.out.println("Child main runing");        Child c1 = new Child();        System.out.println(c1);        Child c2 = new Child(100);        System.out.println(c2);    }}
阅读全文
0 0
原创粉丝点击