Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Top level class extending an inner class

I understand the concept of a top-level class that extends an inner class:

package pkg1;
public class A {
    public class B {
    }
}

package pkg2;
import pk1.A;
public class C extends A.B {
    public C() {
        new A().super();
    }
}

But I cannot figure out any real example that illustrates this. That is, why should we use such implementation?

like image 290
Hicham Moustaid Avatar asked Sep 28 '22 07:09

Hicham Moustaid


1 Answers

That is, why should we use such implementation?

You shouldn't. If C has to create its own enclosing instance, then it is no longer semantically "inner".

This feature is more useful when you are passing the enclosing instance in, which behaves the same as an inner class:

class C extends A.B {
    C(A enclosing) {
        enclosing.super(); // note: invokes a constructor
    }                      //       of the B superclass
}

(Except we can't use a class instance creation expression like someA.new C(). We have to use new C(someA).)

But if you find yourself having to use this, it probably means you've programmed yourself in to a corner. B should probably be a top-level class or static with the "enclosing instance" explicitly passed in.

like image 175
Radiodef Avatar answered Oct 05 '22 06:10

Radiodef