一 问题提出
如果系统中包含多个构造器,其中一个构造器的执行体完全包含另一构造器的执行体,如下图所示,我们怎样组织构造器代码呢?
二 问题解决
1 代码示例
public class Apple
{
public String name;
public String color;
public double weight;
public Apple(){}
// 两个参数的构造器
public Apple(String name , String color)
{
this.name = name;
this.color = color;
}
// 三个参数的构造器
public Apple(String name , String color , double weight)
{
// 通过this调用另一个重载的构造器的初始化代码
this(name , color); //a
// 下面this引用该构造器正在初始化的Java对象
this.weight = weight;
}
}
2 代码分析
- 上面的Apple类里包含了三个构造器,其中第三个构造器通过this来调用另一个枸造器的初始化代码,a处代码调用表明调用该类另一个带两个字符串参数的构造器。
- 使用this调用另一个重载的构器只能在构造器中使用,而且必须作为构造器执行体的第一条语句,使用this调用重载构造器,系统会根据this后括号里的实参来调用形参列表与之对应的构造器。