Base class 构造函数被调用但不应该被调用

Base class constructor being called but shouldn't be

我收到一条错误消息:

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 中的构造函数格式正确。

您需要显式调用基础 class 构造函数(就像您在其他情况下所做的那样):

DerivedClass(String d) {
    super(d);
    System.out.println("Hey look, an argument");
    ...

如果您不这样做,编译器将隐式尝试为基 class 调用无参数构造函数。您的代码中没有这样的构造函数,因此出现错误消息。

问题是,如果您不显式执行此操作,则在构造 DerivedClass 时,编译器将调用 super() 而不带参数。修复很简单:

DerivedClass(String d) {
     super(d);
     // rest of your code
}

有关详细信息,您可以阅读 Java Language Specification, Section 12.4.2 - Detailed Initialization Procedure

Java 规则:-构造函数的第一行是调用超级 class constructor.if 你甚至不写这一行然后编译器在编译期间将 'super()' 调用 super class.

的无参数构造函数

所以当程序执行行 DerivedClass default = new DerivedClass();

执行无参数构造函数,第一行是 super() 调用 super class 的无参数构造函数。(不存在)。

解决方案:-

在 base class

中给出一个无参数构造函数

在派生的 class 参数化构造函数中写入 super("pass a string");第一行