Java 构造函数的深入探讨
1. 从另一个构造函数调用构造函数
在 Java 中,一个构造函数可以调用同一个类的另一个构造函数。例如,有如下的 Test 类:
public class Test {
Test() {
}
Test(int x) {
}
}
若想从无参构造函数调用带 int 参数的构造函数,错误的尝试如下:
public class Test {
Test() {
// Call another constructor
Test(103); // A compile-time error
}
Test(int x) {
}
}
上述代码无法编译。Java 有特殊的方式从一个构造函数调用另一个构造函数,必须使用 this 关键字,就好像它是构造函数的名称一样。正确的代码如下:
public class Test {
Test() {
// Call another constructor
this(103); // OK. Note the use of the keyword this.
}
Test(int x) {
}
}
超级会员免费看
订阅专栏 解锁全文

被折叠的 条评论
为什么被折叠?



