简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM