对象实例化过程

对象实例化过程:

1.看类是否已加载,未加载的话先初始化类。

2.在堆内存中分配空间。

3.初始化父类的属性

4.初始化父类的构造方法

5.初始化子类的属性

6.初始化子类的构造方法

实例:

package com.xm.load;

public class Animal {

    static String str = "I`m a animal!";

    public String str1 = "I`m 10 years old @Animal";

    static {
        System.out.println(str);
        System.out.println("加载父类静态代码块");
    }

    static void doing() {
        System.out.println("This ia a Animal!");
    }

    public Animal() {
        doing();
        System.out.println(str1);
        System.out.println("Animal 对象实例化");
    }


}

class Dog extends Animal{

    static String str = "I`m a dog!";

    private String str1 = "I`m 10 years old @Dog";

    static {
        System.out.println(str);
        System.out.println("加载子类静态代码块");
    }

    static void doing() {
        System.out.println("This ia a dog!");
    }

    public Dog() {
        doing();
        System.out.println(str1);
        System.out.println("Dog 对象实例化");
    }


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

运行结果:

I`m a animal!

加载父类静态代码块

I`m a dog!

加载子类静态代码块

This ia a Animal!

I`m 10 years old @Animal

Animal 对象实例化

This ia a dog!

I`m 10 years old @Dog

Dog 对象实例化

我们来看一下,重写过的父类方法,在加载父类时的情况。

实例:

package com.xm.load;

public class Animal {

    static String str = "I`m a animal!";

    public String str1 = "I`m 10 years old @Animal";

    static {
        System.out.println(str);
        System.out.println("加载父类静态代码块");
    }

    static void doing() {
        System.out.println("This ia a Animal!");
    }

    public void todoing() {
        System.out.println(str1);
        System.out.println("加载子类的重写方法");
    }

    public Animal() {
        doing();
        todoing();
        System.out.println("Animal 对象实例化");
    }


}

class Dog extends Animal{

    static String str = "I`m a dog!";

    private String str1 = "I`m 10 years old @Dog";

    static {
        System.out.println(str);
        System.out.println("加载子类静态代码块");
    }

    static void doing() {
        System.out.println("This ia a dog!");
    }

    public void todoing() {
        System.out.println(str1);
        System.out.println("加载子类的重写方法");
    }

    public Dog() {
        doing();
        System.out.println("Dog 对象实例化");
    }


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

结果:

I`m a animal!

加载父类静态代码块

I`m a dog!

加载子类静态代码块

This ia a Animal!

null

加载子类的重写方法

Animal 对象实例化

This ia a dog!

Dog 对象实例化

由此可见,null代表着加载父类构造方法时,调用的todoing( )方法是子类的方法,且子类的属性的初始化过程发生在父类构造方法之后。

原文地址:https://www.cnblogs.com/TimerHotel/p/java_newObject.html