对象实例化过程

对象实例化过程:

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( )方法是子类的方法,且子类的属性的初始化过程发生在父类构造方法之后。

posted @   零度微笑  阅读(700)  评论(0编辑  收藏  举报
编辑推荐:
· 如何在 .NET 中 使用 ANTLR4
· 后端思维之高并发处理方案
· 理解Rust引用及其生命周期标识(下)
· 从二进制到误差:逐行拆解C语言浮点运算中的4008175468544之谜
· .NET制作智能桌面机器人:结合BotSharp智能体框架开发语音交互
阅读排行:
· 想让你多爱自己一些的开源计时器
· Cursor预测程序员行业倒计时:CTO应做好50%裁员计划
· 大模型 Token 究竟是啥:图解大模型Token
· 用99元买的服务器搭一套CI/CD系统
· 如何在 .NET 中 使用 ANTLR4
点击右上角即可分享
微信分享提示