对象的三种初始化方法

1、成员变量赋初值

public class test1
{
	int number = 0;
	int times = 0;
	String name = "~";
}

2、构造函数

public class test1
{
	int number;
	int times;
	String name;
	
	public test1()
	{
		System.out.println("执行默认构造函数");
	}
}
	public test1(int times)
	{
		System.out.println("执行构造函数1");
		this.times = times;
	}
}

3、构造函数块

public class test1
{
	int number;
	int times;
	String name;
	{
		System.out.println("执行构造代码块");
		number = 7;
		name = "xu";
	}
}

一、初探执行优先级:(在没有构造代码块的情况下)

public class test1
{
	int number = 0;
	int times = 0;
	String name = "~";
	public test1()
	{
		System.out.println("执行默认构造函数");
	}
	public test1(int times)
	{
		System.out.println("执行构造函数1");
		this.times = times;
	}
	public test1(int number,int times,String name)
	{
		System.out.println("执行构造函数2");
		this.number = number;
		this.times = times;
		this.name = name;
	}
	
	public static void main(String[] args)
	{
		test1 test = new test1();
		System.out.println(test.number);
		test1 tes = new test1(1);
		System.out.println(tes.number);
		test1 te = new test1(1,1,"wei");
		System.out.println(te.number);
	}
}

运行结果: 

对象的三种初始化方法_第1张图片

现象:构造函数初始化覆盖成员变量的初值

 结论:成员变量赋初值 > 构造函数

二、再探执行优先级(加入构造代码块)

public class test1
{
	int number = 0;
	int times = 0;
	String name = "~";
	public test1()
	{
		System.out.println("执行默认构造函数");
	}
	public test1(int times)
	{
		System.out.println("执行构造函数1");
		this.times = times;
	}
	public test1(int number,int times,String name)
	{
		System.out.println("执行构造函数2");
		this.number = number;
		this.times = times;
		this.name = name;
	}
	{
		System.out.println("执行构造代码块");
		number = 7;
		name = "xu";
	}
	public static void main(String[] args)
	{
		test1 test = new test1();
		System.out.println(test.number);
		test1 tes = new test1(1);
		System.out.println(tes.number);
		test1 te = new test1(1,1,"wei");
		System.out.println(te.number);
	}
}

 运行结果:

对象的三种初始化方法_第2张图片

现象:

1)先打印“执行构造代码块”,后打印“执行构造函数”

2)构造代码块初始化覆盖构造函数初始化,成员变量赋初值并没有覆盖构造代码块初始化

 结论:成员变量赋初值 > 构造代码块 > 构造函数

(其实在最前面还有赋默认值0和null) 

你可能感兴趣的:(java基础,java)