【JAVA学习路-think in java】p86:构造器中调用构造器+this

package pkg;

class Flower{
	
	int n=0;
	String s="Initial string";
	
	//1st constructor
	Flower(int a){
		n=a;
		System.out.println("Flower(int a):execute this, and n="+n);
	}
	
	//2nd constructor
	Flower(String ss){
		ss=s;
		System.out.println("Flower(String ss):execute this, and s="+s);
	}
	
	//3rd constructor
	Flower(String ss,int a){
		this(a);//******************* this is used as a function *************
		//this(ss);//CAN NOT CALL TWO constructor
		this.s=ss;//allowed
		System.out.println("Flower(String ss,int a):execute this, and s="+s);
	}
	
	//4th constructor
	Flower(){
		this("hello",47);//constructor call must be the first statement in a constructor
		System.out.println("Flower():excute this");
	}
	
	//1st function
	void flowerPrint() {
		//this(11);//not allowed
		this.n=9527;
		System.out.println("Result:n="+n+",s="+s);
	}
	
}


public class p86 {
	public static void main(String[] args){
		Flower f= new Flower();
		f.flowerPrint();
	}	
}

output:

Flower(int a):execute this, and n=47
Flower(String ss,int a):execute this, and s=hello
Flower():excute this
Result:n=9527,s=hello
 

【总结】:

1、this,可以当作的“当前对象”的对象名使用。如this.value,this.method(),以及this(arg1,arg2)(构造函数之名)

2、构造函数中调用其他构造函数,只能调用一次,且必须首句调用、且只能由构造函数调用构造函数

 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值