栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

对象创建的过程

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

对象创建的过程

流程结果

对象构建之前

    父类 static property 声明 赋值父类 static{}子类 static property 声明 赋值子类 static{}

对象开始创建

    进入子类 constructor() 默认spuer() 调用进入父 类 constructor()父类 property 开始声明 赋值运行 not static{}——————————————返回 子类 constructor()子类 property 声明 赋值运行 not static{}
物料
public class Test08 {
    public static void main(String[] args) {
        Zi zi = new Zi();
    }
}
class Fu{
    private static int i = getNum("(1)i"); // 3
    private int j = getNum("(2)j");
    static{    // 1
        print("(3)父类静态代码块");
    }
    {
        print("(4)父类非静态代码块,又称为构造代码块");
    }
    Fu(){
        print("(5)父类构造器");
    }
    public static void print(String str){
        System.out.println(str + "->" + i);
    }
    public static int getNum(String str){
        print(str);
        return ++i;
    }
}
class Zi extends Fu{
    private static int k = getNum("(6)k"); //
    private int h = getNum("(7)h");
    static{  // 2
        print("(8)子类静态代码块");
    }
    {
        print("(9)子类非静态代码块,又称为构造代码块");
    }
    Zi(){
        print("(10)子类构造器");
    }
    public static void print(String str){
        System.out.println(str + "->" + k);
    }
    public static int getNum(String str){
        print(str);
        return ++k;
    }
}

贴上运行结果

来debug 一步步分析详解

这里对象是从new 开始

new 开始之前

虽然感觉实际编写中没人这样去写代码,但还是了解了一下 一下阶段比较无用
此时对象还没有被构建

    运行 父 类的 static 变量 声明—— static 变量 赋值调用的 static 方法 运行到static 方法 //完成赋值运行 父 类的 static{} 代码块————————————————开始 运行 子类 static 变量 声明—— 可以直接赋值 使用 static 完成赋值运行 子类 static{} 代码块

到目前为止 都开没开始运行 进行对象的创建,
说实话,我也不知道以后在开发中,谁会这样去写类,这些顺序有啥妙用

开始 调用 构造器了

debug 了半天。终于又回到了开始的地方

    进入了子类构造器 运行第一行代码 这里有隐藏的 super()

    进入 父 类的构造器。 完成父类 构造器 运行

    此时 不会返回子类构造, 开始 成员变量赋值

    运行 父 类 非static{}

    ——————————————

    开始运行 构造器的{}
    到此 父类的全部内容都算完成,接下来就是子类完成一样的过程

    回到 子类 。给子类 成员变量 赋值

    运行 非static{} 代码块

    运行 构造器{}

到这里整个类终于在完成了创建 全是细节,但又感觉没啥用= =

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/708348.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号