我们在一个类中,可以在一个构造器中显式的调用本类的其他构造器。
如:
public class Person {
private String name;
//构造器一
public Person() {
}
//构造器二
public Person(String name) {
this(); //调用构造器一
this.name = name;
}
}
我们接下来谈谈其中需要我们注意的地方。
1.通过"this(形参列表)"的方式,一定是调用本类中的构造器,而不能是其他类的。(这个想必不用多说了吧)
2.只能调用其他构造器,而不能在方法体中调用自身。
//错误的调用方式
public Person() {
this();
}
这样就是一种递归调用本身构造器的方式,没有递归的结束条件,肯定报错了。
(这是Eclipse中的报错信息 ==》“Recursive constructor invocation Person()” 翻译过来也就是递归调用自身构造器的意思)
3.“this(形参列表)” 一定要是构造器中的第一条语句。
正确的调用方式:
public Person(String name) {
this(); //调用无参构造器
this.name = name;
}
错误的调用方式:
public Person(String name) {
this.name = name;
this(); //调用构造器一
}
Eclipse中的错误信息===》“Constructor call must be the first statement in a constructor” (构造方法调用必须是构造方法中的第一个语句)
这是Java定义的规范,我们记住就好
4.只能调用一个其他的构造器,而不能调用多个
错误的调用方式:
public Person(int age, String name) {
this(); //调用无参构造器
this(name); //调用参数为name的构造器
}
这个可以用第3点来解释,我们可以看到 this(name) 是这个构造器中的第二条语句,显然不符合第3点的规则(“this(形参列表)” 一定要是构造器中的第一条语句)