Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make an outer class inherited from an inner class?

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.

like image 387
zvrba Avatar asked Apr 16 '11 09:04

zvrba


2 Answers

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.

like image 50
Paŭlo Ebermann Avatar answered Oct 27 '22 14:10

Paŭlo Ebermann


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;
    }
}
like image 43
WhiteFang34 Avatar answered Oct 27 '22 13:10

WhiteFang34