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语句时,只能出现在第一行,构造方法要先执行,乳沟构造方法中还有初始化,那就执行更细节的初始化

例:
在这里插入图片描述

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 );
	}
}
  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值