类和对象的初始化过程

在这里插入图片描述
在这里插入图片描述

/*
 * 父类的初始化<clinit>:
 * (1)j = method();
 * (2)父类的静态代码块
 * 
 *  父类的实例化方法:
 * (1)super()(最前)
 * (2)i = test();
 * (3)父类的非静态代码块
 * (4)父类的无参构造(最后)
 * 
 * 非静态方法前面其实有一个默认的对象this
 * this在构造器(或<init>)它表示的是正在创建的对象,因为这里是在创建Son对象,所以
 * test()执行的是子类重写的代码(面向对象多态)
 * 
 * 这里i=test()执行的是子类重写的test()方法
 */
public class Father{
	private int i = test();
	private static int j = method();
	
	static{
		System.out.print("(1)");
	}
	Father(){
		System.out.print("(2)");
	}
	{
		System.out.print("(3)");
	}
	
	
	public int test(){
		System.out.print("(4)");
		return 1;
	}
	public static int method(){
		System.out.print("(5)");
		return 1;
	}
}
/*
 * 子类的初始化<clinit>:
 * (1)j = method();
 * (2)子类的静态代码块
 * 
 * 先初始化父类:(5)(1)
 * 初始化子类:(10)(6)
 * 
 * 子类的实例化方法<init>:
 * (1)super()(最前)      (9)(3)(2)
 * (2)i = test();    (9)
 * (3)子类的非静态代码块    (8)
 * (4)子类的无参构造(最后) (7)
 * 
 * 因为创建了两个Son对象,因此实例化方法<init>执行两次
 * 
 * (9)(3)(2)(9)(8)(7)
 */
public class Son extends Father{
	private int i = test();
	private static int j = method();
	static{
		System.out.print("(6)");
	}
	Son(){
//		super();//写或不写都在,在子类构造器中一定会调用父类的构造器
		System.out.print("(7)");
	}
	{
		System.out.print("(8)");
	}
	public int test(){
		System.out.print("(9)");
		return 1;
	}
	public static int method(){
		System.out.print("(10)");
		return 1;
	}
	//注意在 子类和父类组成的联合体中,父类的test() 方法已经被子类的同名方法 override了 找不到了
	public static void main(String[] args) {
		Son s1 = new Son();//(5) (1)  (10) (6) (9) (3) (2)(9) (8) (7)
		System.out.println();
		Son s2 = new Son();// (9) (3) (2)(9) (8) (7)
	}
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值