在代码中,我为重载构造函数提供了调用无参数构造函数的参数,在这种情况下,它又应该调用对象类的构造函数。那么如何使用this()关键字正确执行程序而不是直接调用构造函数。
public class S {
S() {
System.out.println("S()");
}
S(int i) {
this();
S();// The method S is undefined for type S
System.out.println("S(int i)");
}
public static void main(String[] args) {
S obj1 = new S();
System.out.println("----------");
S obj2 = new S(10);
System.out.println("----------");
}
}
最佳答案
从句法上讲,S()
是一个方法调用,但您没有名为S
的方法。
this();
是在同一个类中使用另一个构造函数的特殊语法。
为了说明这一点,我补充说:
void S() {
System.out.println("Method S()");
}
现在编译,输出是:
S()
----------
S()
Method S()
S(int i)
----------
关于java - 与显式构造函数调用混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28752257/