How can I make something like this work:
class Outer {
int some_member;
abstract class InnerBase {
abstract void method();
}
}
class OuterExtendsInner extends Outer.InnerBase {
OuterExtendsInner(Outer o) { o.super(); }
void method() {
// How do I use some_member here?
// Writing Outer.this.some_member -> error about Outer not being an enclosing class
// Writing just some_member -> no-go, either
}
}
The workaround is to have a method in InnerBase that returns Outer.this and call THAT from derived classes, but is there another way?
I primarily want to extend the InnerBase from outside in order to have better code-organization, but I could move all derived classes into Outer.
The problem here is that the synthetic field which links InnerBase
to Outer
is a private field. Thus, we can only access the outer object from within InnerBase
, or if some method or field there provides a reference to the same object.
You could do this in OuterExtendsInner
:
class OuterExtendsInner extends Outer.InnerBase {
Outer o;
OuterExtendsInner(Outer o) {
o.super();
this.o = o;
}
void method() {
// now you can reference o.some_member
int x = o.some_member;
}
}
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