JAVA 对象的初始化顺序

1. 这是个笔记.####

HelloParent.class

public class HelloParent {
    helloY y = new helloY();
    static {
        System.out.println("parent static block");
    }
    public HelloParent() {
        System.out.println("parent construct");
    }
}

HelloChild.class

public class HelloChild extends HelloParent {   
    helloY y = new helloY();    
    static {        
        System.out.println("child static block");    
    }     
    public HelloChild() {
        System.out.println("child construct");    
    }    
    public static void main(String[] args) {
        new HelloChild ();   
    }
}

helloY.class

public class helloY {
    helloY() {
        System.out.println("this is Y");
    }
}

这里我们先看运行的结果是什么:

parent static block
child static block
this is Y
parent construct
this is Y
child construct

2.我简单说下这个过程,如果说得不对,请指出,谢谢.####

这里我们可以看到主函数 main 方法HelloChild.class
所以我们运行 HelloChild.class

当执行new HelloChild()时,由于是 HelloChild 继承了HelloParent 类 ,先执行父类的方法.

1.它首先去看父类里面有没有静态代码块,如果有,它先去执行父类里面静态代码块里面的内容#####
2.再去执行子类(自己这个类)里面的静态代码块#####
3.然后去看父类有没有非静态代码块,如果有就执行父类的非静态代码块#####
4.接着执行父类的构造方法#####
5.紧接着它会去看子类有没有非静态代码块,如果有就执行子类的非静态代码块#####
6.最后去执行子类的构造方法#####

以上是基于本例来讲解的一个对象初始化过程,如果某些方法没有,就不会去执行.

3.一些注意事项####

静态代码块只执行一次
主函数 main 方法

    public static void main(String[] args) {
        new HelloChild ();   
        new HelloChild ();
    }

这次运行的结果是

parent static block
child static block
this is Y
parent construct
this is Y
child construct
this is Y
parent construct
this is Y
child construct

你们也发现了.静态代码块只会执行一次.

4.总结####

1.如果有些代码必须在项目启动的时候就执行,需要使用静态代码块,这种代码是主动执行的;#####
2.需要在项目启动的时候就初始化,在不创建对象的情况下,其他程序来调用的时候,需要使用静态方法,这种代码是被动执行的.
3.静态方法在类加载的时候 就已经加载 可以用类名直接调用 . 比如main方法就必须是静态的 这是程序入口#####
4.两者的区别就是:静态代码块是自动执行的;静态方法是被调用的时候才执行,而且不新建对象.#####

欢迎指正.

你可能感兴趣的:(JAVA 对象的初始化顺序)