【问题标题】:How to instantiate subclass from within a superclass如何从超类中实例化子类
【发布时间】:2013-10-08 05:00:37
【问题描述】:

以下代码有什么问题,我该如何解决?我的目标是在我的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

【问题讨论】:

    标签: java inheritance constructor subclass superclass


    【解决方案1】:

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

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

    public Test3(String printComment2) {
        super(printComment2);
        System.out.println(printComment2);
    }
    

    【讨论】:

    • 因此,如果我要放入适当的构造函数以便可以调用 super(),那么对 super() 的调用基本上不会执行任何操作,并且可以让我获得我在帖子中指定的功能?
    • 如果给Test2添加一个无参数的构造函数,编译器会自动调用它。这是否有效取决于您。
    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

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

      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);
        }
        

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-06-13
        • 2023-04-08
        • 1970-01-01
        • 1970-01-01
        • 2019-06-28
        • 2015-09-18
        相关资源
        最近更新 更多