Search code examples
javainheritanceconstructorsubclasssuperclass

The constructor of an inner class of a superclass is undefined if there is argument in the super-constructor


I have a class A, and A_sub is an inner class of 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");
    }

}

Then I have a class Main (which extends A) with a method main. Main also have an inner class A_sub (which extends A.A_sub). But I got an error message at the line of super() saying "The constructor A.A_sub() is undefined". How can I got it solved?

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

    }
}

Solution

  • The really is no constructor as A$A_sub.A_sub() - the constructor you have takes an A_sub argument. One way to solve this is pass Main$A_sub.A_sub's argument to its parent's constructor:

    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
    }