0

以下代码有什么问题,我该如何解决?我的目标是在我的main方法中使用超类。这个超类对象应该自己创建(在其内部状态)其子类的实例。这样做的目的是因为子类只需要超类的状态来工作,而且因为子类需要做的所有操作都只对超类很重要。

public class Test {
    public static void main(String[] args) {
        Test2 testSuperclass = new Test2("success #1");
    }   
}

class Test2 {
    public Test2(String printComment) {
        System.out.println(printComment);
        Test3 testSubclass = new Test3("success #2");
    }
}

class Test3 extends Test2 {
    public Test3(String printComment2) {
        System.out.println(printComment2);
    }
}

构造Test3函数正在生成错误Implicit super constructor Test2() is undefined. Must explicitly invoke another constructor

4

3 回答 3

3

构造函数要做的第一件事是调用超类的构造函数。

super()通常,您看不到这一点,因为如果您不指定另一个构造函数,Java 编译器会自动插入对非参数构造函数 ( ) 的调用。但在您的情况下,Test2 中没有非参数构造函数(因为您创建了另一个需要字符串的构造函数)。

public Test3(String printComment2) {
    super(printComment2);
    System.out.println(printComment2);
}
于 2013-10-08T05:02:52.023 回答
0

您可以执行以下任一操作:

  1. 如果您只想让您的代码在没有任何额外打印或创建对象的情况下工作,请创建一个无参数构造函数:

    class Test2 {
        public Test2(){
        }
        public Test2(String printComment) {
            System.out.println(printComment);
            Test3 testSubclass = new Test3("success #2");
        }
    }
    
    class Test3 extends Test2 {
        public Test3(String printComment2) {
            System.out.println(printComment2);
        }
    }
    
  2. 或者另一种方式就像 Thio 提到的那样:

    public Test3(String printComment2) {
      super(printComment2);
      System.out.println(printComment2);
    }
    
于 2013-10-08T05:38:33.567 回答
0

添加到 Thilo 的答案中,当您没有显式定义超级(对父构造函数的调用)时,隐式调用将被简单地称为“super()”。因此,您实际上允许调用 Test2 的构造函数,但不传递导致未定义错误的字符串。

于 2013-10-08T05:06:56.353 回答