Java基础知识-对象初始化

1. Java对象的初始化顺序如下:
   父类 static字段及 static块 -> 子类 static字段及 static块 
   -> 父类非 static字段及非 static块 -> 父类构造方法 
   -> 子类非 static字段及非 static块 -> 子类构造方法 
2. 示例代码如下:
package org.demo;

public class InitDemo {
    public static void main(String[] args) {
        new Child("init");
    }
}
class Parent {
    private static int total = 1;
    private int id = print("id");
    
    private static Parent p1 = new Child("child1");
    private static Parent p2 = new Child("child2");
    private static int i = print("i");
    private static int j = 99;
    static {
        print("静态块");
    }
    
    {
        print("构造块");
    }
    public Parent(String str) {
        System.out.println("parent, " + (total++) + ":" + str + " i=" + i + " j=" + j);
        ++i;
        ++j;
        System.out.println(toString());
    }
    
    public static int print(String str) {
        System.out.println("parent, " + (total++) + ":" + str + " i=" + i + " j=" + j);
        ++j;
        return ++i;
    }
    public String toString() {
        return "parent, total=" + total + " id=" + id;
    }
}
class Child extends Parent {
    private static int total = -1;
    private int id = -1;
    
    public Child(String name) {
        super(name);
        if (total < 0) {
            total = 1;
        } else {
            total++;
        }
        id=total;
        System.out.println(toString());
    }
    
    public static int print(String str) {
        System.out.println(" child, str=" + str);
        return 0;
    }
    public String toString() {
        return " child, total=" + total + " id=" + id;
    }
}
/*
parent, 1:id i=0 j=0
parent, 2:构造块 i=1 j=1
parent, 3:child1 i=2 j=2
 child, total=0 id=0
 child, total=1 id=1
parent, 4:id i=3 j=3
parent, 5:构造块 i=4 j=4
parent, 6:child2 i=5 j=5
 child, total=1 id=0
 child, total=2 id=2
parent, 7:i i=6 j=6
parent, 8:静态块 i=7 j=99
parent, 9:id i=8 j=100
parent, 10:构造块 i=9 j=101
parent, 11:init i=10 j=102
 child, total=-1 id=0
 child, total=1 id=1
*/
3. 分析如下:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值