【问题标题】:The constructor of an inner class of a superclass is undefined if there is argument in the super-constructor [duplicate]如果超构造函数中有参数,则超类内部类的构造函数未定义[重复]
【发布时间】:2020-10-31 12:07:11
【问题描述】:

我有一个类A,而A_sub 是A 的一个内部类。

public class A {

    protected class A_sub { 
        int A_sub_x = 1;
        A_sub parent;
    
        A_sub(A_sub obj_A_sub) {
            System.out.println("Constructor A.A_sub");
            parent = obj_A_sub;
        }
    }

    public A() {
        System.out.println("Constructor A");
    }

}

然后我有一个类Main(它扩展了A)和一个方法main。 Main 也有一个内部类 A_sub(它扩展了 A.A_sub)。但我在super() 行收到一条错误消息,说“构造函数 A.A_sub() 未定义”。怎么解决?

class Main extends A{

    public Main() {
    }

    private class A_sub extends A.A_sub{ 
        int A_sub_z;

        A_sub(A_sub obj_A_sub) {
            super();
            System.out.println("Constructor Main.A_sub");
            A_sub_z = 3;
        }
    }


    public static void main(String args[]) {

        Main obj = new Main();
        A_sub obj_sub = obj.new A_sub(null);

        System.out.println(obj_sub.A_sub_x);
        System.out.println(obj_sub.A_sub_z);

    }
}

【问题讨论】:

  • 因为父类没有默认构造函数,所以报错!

标签: java inheritance constructor subclass superclass


【解决方案1】:

因为 Main.A_sub 类扩展了 A.A_sub 并且它具有非默认构造函数,所以您必须传递所需的参数

    private class A_sub extends A.A_sub {

        A_sub(A_sub obj_A_sub) {
            super(null); // Pass the required argument
            //....
        }
    }

【讨论】:

    【解决方案2】:

    只需在类 A_sub 中创建一个空的构造函数

    所以,内部类 A_sub 应该是

    protected class A_sub {
            int A_sub_x = 1;
            A_sub parent;
    
            A_sub(A_sub obj_A_sub) {
                System.out.println("Constructor A.A_sub");
                parent = obj_A_sub;
            }
    
            public A_sub() {
    
            }
        }
    

    【讨论】:

      【解决方案3】:

      真的没有像A$A_sub.A_sub() 那样的构造函数——你的构造函数接受A_sub 参数。解决此问题的一种方法是将Main$A_sub.A_sub 的参数传递给其父构造函数:

      class Main extends A{
      
          private class A_sub extends A.A_sub{ 
              int A_sub_z;
      
              A_sub(A_sub obj_A_sub) {
                  super(obj_A_sub);
                  // Here-^
                  System.out.println("Constructor Main.A_sub");
                  A_sub_z = 3;
              }
          }
      
          // The rest of Main's constructors and methods have been snipped for brevity
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-11-29
        • 2021-07-24
        • 2013-10-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多