java构造代码块与构造方法

构造代码块
  • 特点:对象一建立就运行了,而且优先于构造函数执行
  • 作用:给对象进行初始化
  • 构造代码块与构造方法区别:
  • 构造代码块是给所有的对象进行统一的初始化
  • 构造方法是对应的对象进行初始化
public class test10 {
	public static void main(String[] args){
		Person2 A = new Person2();
		Person2 B = new Person2("小虎鲸");
		System.out.println(A);
		System.out.println(B);
	}
}

class Person2{
	String name;
	//无参构造方法
	Person2(){
		System.out.println("无参构造方法");
	}
	//有参构造方法
	Person2(String name){
		this.name = name;
		System.out.println("有参构造方法");
	}
	//构造代码块
	{
		System.out.println("构造代码块");
	}
}


public class test11_student {
	public static void main(String[] args){
		Student2 A = new Student2();
		Student2 B = new Student2("小虎鲸",5);
		System.out.println(A);
		System.out.println(B);
	}
}

class Student2{
	String name;
	int age;
	Student2(){
		System.out.println("无参构造函数");
	}
	Student2(String name, int age){
		this.name = name;
		this.age = age;
		System.out.println(this.name+this.age);
	}
	{
		System.out.println("coding");
	}
}
构造函数之间的调用
public class test12 {
	public static void main(String[] args){
		Student3 A = new Student3("小虎鲸");
		Student3 B = new Student3("彩虹鲸",12);
		System.out.println(A);
		System.out.println(B);
	}
}

class Student3{
	String name;
	int age;
	Student3(){
		System.out.println("无参构造函数");
	}
	Student3(String name){
		this();
		this.name = name;
		System.out.println("aaa");
	}
	Student3(String name, int age){
		this(name);
		this.age = age;
		System.out.println("bbb");
	}
}
  • 构造函数之间的调用只能通过this语句来完成
  • this 用来区分局部变量和成员变量同名的情况
  • this 代表本类对象,this代表它所在函数所属对象的引用
  • 构造函数之间调用this语句时,只能出现在第一行,构造方法要先执行,乳沟构造方法中还有初始化,那就执行更细节的初始化

例:
java构造代码块与构造方法_第1张图片

public class test13 {
	public static void main(String[] args){
		Student5 A = new Student5("karry",21,"China");
		System.out.println(A);
	}
}

class Student5{
	String name;
	int age;
	String country;
	Student5(String name){
		this.name = name;
		System.out.println(this.name);
	}
	Student5(String name, int age){
		this(name);
		this.age = age;
		System.out.println(this.age);
	}
	Student5(String name, int age, String country){
		this(name,age);
		this.country = country;
		System.out.println(this.country );
	}
}

你可能感兴趣的:(java)