1

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

    }
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
H42
  • 725
  • 2
  • 9
  • 28

3 Answers3

1

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
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
0

Just create an empty constructor in class A_sub

So, inner class A_sub should be

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() {

        }
    }
karthick M
  • 192
  • 1
  • 13
0

Because the class Main.A_sub extends A.A_sub and it has non-default constructor you have to pass the required argument

    private class A_sub extends A.A_sub {

        A_sub(A_sub obj_A_sub) {
            super(null); // Pass the required argument
            //....
        }
    }
0xh3xa
  • 4,801
  • 2
  • 14
  • 28