标签:Java
如下写了三个构造器Test(int i)
,Test(String s)
,Test(int i, String s)
,其中第三个构造器以this(i)
调用了第一个构造器,并且只能在最开始调用一次,不能再继续调用第二个构造器了。且只有在构造函数里能够用this(.)
调用构造器,一般的函数里不能调用构造器(line 9)。
如果传入参数和类属性的名称一样,产生冲突,则用this.xxx
来指代类属性。没有冲突的话可以不写this.
。
public class Test{
private int i = 0;
Test(int i) {
this.i = i + 1;
System.out.println("parameter:" + i + " member of Test:" + this.i);
}
void pr() {
System.out.println("print member i:" + i);
//this(100); // not constructor, can't call Test(int i)
}
Test(String s){
System.out.println("String s:" + s);
}
Test(int i, String s) {
this(i); // call Test(int i)
//this(s); // can't call twice
System.out.println("member of Test:" + this.i);
}
public static void main(String[] args) {
Test tt0 = new Test(10);
tt0.pr();
Test tt1 = new Test("ok");
Test tt2 = new Test(20, "ok again!");
}
}