我收到一条错误消息:
DerivedClass.java:6: error: constructor BaseClass in class BaseClass cannot be applied to given types;
DerivedClass(String d) {
^
required: String
found: no arguments
reason: actual and formal argument lists differ in length
1 error
这是我的代码:
class BaseClass {
BaseClass(String f) {
System.out.println(f);
System.out.println("BaseClass time");
}
}
public class DerivedClass extends BaseClass {
DerivedClass() {
super("You did not pass an argument to your object.");
System.out.println("It's DerivedClass time");
}
DerivedClass(String d) {
System.out.println("Hey look, an argument");
System.out.println(d);
System.out.println("It's DerivedClass time");
}
public static void main(String[] args) {
DerivedClass defauld = new DerivedClass();
DerivedClass custom = new DerivedClass("Ayyyyy");
}
}
做什么?我觉得没有理由让它运行失败。据我所知,DerivedClass 中允许您传递字符串的构造函数的格式正确。
最佳答案
问题是,如果您不显式执行此操作,则在构造 DerivedClass 时,编译器将调用不带参数的 super()
。修复方法很简单:
DerivedClass(String d) {
super(d);
// rest of your code
}
有关更多信息,您可以阅读Java Language Specification, Section 12.4.2 - Detailed Initialization Procedure
关于java - 基类构造函数被调用但不应该被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28459678/