Java构造方法总结

构造方法: 方法名是类名([参数列表]){}
特点1: 构造方法没有返回值部分, void 不能有,不允许 final 和 static 修饰

public class Fourth {
	//特点1:构造方法没有返回值部分, void 不能有,不允许 final 和 static 修饰
	int age;
	String name;
	String mobile;
	String address;
	Fourth(int a,String n,String m,String add){

	}

	public static void main(String[] args) {

	}
	
}

特点2: 一个类中默认有无参构造方法,当定义了一个有参数构造方法时,则默认无参构造方法隐藏

public class Fourth {
	
	int age;
	String name;
	String mobile;
	String address;
	Fourth(int a,String n,String m,String add){//有参

	}
	Fourth(int a,String n){
	
	}
	public static void main(String[] args) {
	Fourth a = new Fourth();//错误
	Fourth a = new Fourth(18,"lihua","176*****715","中国");//正确
	}
	
}

特点3: 一个类中根据需要可以定义多个构造方法,这是重载的体现

public class Fourth {

	int age;
	String name;
	String mobile;
	String address;
	Fourth(int a,String n,String m,String add){

	}
	Fourth(int a,String n){
	
	}
	public static void main(String[] args) {

	}
	
}

特点4: 为了简化代码,类中构造方法可以互相调用,this(实参列表),但必须置于构造方法有效代码第一行

public class Fourth {
	//为了简化代码,类中构造方法可以互相调用,this(实参列表),但必须置于构造方法有效代码第一行
	int age;
	String name;
	String mobile;
	String address;
	Fourth(int a,String n,String m,String add){//有参
		this(a, n);//调用下面构造方法
//		age = a;
//		name = n;
		mobile = m;
		address = add;
		//上面四行代码就是为成员变量赋值的过程
	}
	
	Fourth(int a,String n){
		age = a;
		name = n;
	}
	public static void main(String[] args) {
		//构造方法使用new来调用
		Fourth a = new Fourth(18,"lihua","176*****715","中国");

		
		Fourth b = new Fourth(13,"xiaoming","132*****765","中国");

		System.out.println(a.name);
		System.out.println(b.address);
		
		Fourth c = new Fourth(18,"光头强");
		System.out.println(c.name);
	}
	
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值