public class Test {
static int i = 1;
public Test(Test s) {
System.out.println(s.i+1);
}
public Test() {
this(new Test());
}
private Test ts(){
new Test();
return this;
}
public static void main(String[] args) throws Exception {
System.out.println(new Test().ts().i);
}
}1,请解释以上代码
2,如果代码有错请指出
3,如果代码没错请写出输出结果
static int i = 1;
public Test(Test s) {
System.out.println(s.i+1);
}
public Test() {
this(new Test());
}
private Test ts(){
new Test();
return this;
}
public static void main(String[] args) throws Exception {
System.out.println(new Test().ts().i);
}
}1,请解释以上代码
2,如果代码有错请指出
3,如果代码没错请写出输出结果
public Testa() {
this(new Testa());
}
看书看到构造函数这块就自己边试边验证了
看书看到构造函数这块就自己边试边验证了
反正这代码有问题,private Test ts(){
new Test();
return this;
}这段代码会不停的new Test对象,你想测试构造器也是这样子验证的吧!
是,这块是有问题的,不停的new对象了
确切的说, 应该是
public Test() {
this(new Test());
}
这段有问题
this(new Test());
} 其实我这段的代码的本意是想使用this关键字调用
public Test(Test s) {
System.out.println(s.i+1);
}这个构造函数的,所以this(new Test());的本意是想传个Test对象的参数,结果导致了无参的构造器死循环了