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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With