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、构造函数中调用其他构造函数,只能调用一次,且必须首句调用、且只能由构造函数调用构造函数。