user3026485
user3026485

Reputation: 79

extending inner clsses in java

public class Questions {
    public static void main(String[] args) {

        D d = new D();
    }
}

class A {
    A() {
        System.out.println("A");
    }
}

class B extends A {
    B() {
        System.out.println("B");
    }

    class C {
        C() {
            System.out.println("C");
        }
    }
}

class D extends B.C {
    D() {//compilation error
        System.out.println("D");
    }
}

This shows an error while D is created that some intermediate constructor call. please tell me how do I extend such inner classes and what is wrong with this code. Thank you.

Upvotes: 0

Views: 55

Answers (2)

Pshemo
Pshemo

Reputation: 124225

All non-static inner classes need to have reference to instance of its outer class. If you want to extend such class you need to assure that object which will be used as base will have instance of its outer object. So you can do something like this:

class D extends B.C {
    D(B b) {
        b.super();
        System.out.println("D");
    }
}

and use

D d = new D(new B());

Upvotes: 1

koljaTM
koljaTM

Reputation: 10262

You have to make the class C static so that it can be accessed from outside B.

class B extends A {

B () {
    System.out.println("B");
}

static class C {

    C () {
        System.out.println("C");
    }
}
}

Apart from a theoretical question, why would you do this?

Upvotes: 4

Related Questions