ceving
ceving

Reputation: 23824

How to access an inner class from an enclosing class in Java?

I am still fighting with Java's references. I am not sure if I will ever understand them. Can anybody help me?

A non static inner class can access the enclosing class via Outer.this. But how can the outer class access the inner this?

See this example:

class cycle
{
  abstract static class Entity
  {
    abstract static class Attribute
    {
      abstract static class Value
      {
        abstract Attribute attribute ();
      }

      abstract Entity entity ();
      abstract Value value ();
    }
  }

  static class Person extends Entity
  {
    class FirstName extends Attribute
    {
      class StringValue extends Value
      {
        Attribute attribute () { return FirstName.this; }
      }

      Entity entity () { return Person.this; }
      Value value () { return this.StringValue.this; }
    }
  }

  public static void main (String[] args)
  {
    Person p = new Person();
  }
}

StringValue can access FirstName and FirstName can access Person. But how can FirstName access StringValue?

I get the error <identifier> expected in the implementation of value()? What is the correct syntax?

Upvotes: 2

Views: 125

Answers (2)

ceving
ceving

Reputation: 23824

Thanks to Sotirios this is the corrected version of the code from my question.

class cycle
{
  abstract static class Entity
  {
    abstract static class Attribute
    {
      abstract static class Value
      {
        abstract Attribute attribute ();
      }

      abstract Entity entity ();
      abstract Value value ();
    }
  }

  static class Person extends Entity
  {
    Attribute firstname = new Attribute()
      {
        Value value = new Value()
          {
            Attribute attribute () { return firstname; }
          };

        Entity entity () { return Person.this; }
        Value value () { return value; }
      };
  }

  public static void main (String[] args)
  {
    Person p = new Person();
  }
}

Upvotes: 1

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279970

An Inner class is a member of the Outer class, but it is not a field, ie. there isn't only maximum of one.

You can do

Outer outer = new Outer();
Outer.Inner inner1 = outer.new Inner();
Outer.Inner inner2 = outer.new Inner();
Outer.Inner inner3 = outer.new Inner();
... // ad nauseam

Although each Inner object is related to its outer instance, the Outer instance knows nothing about the Inner instances unless you tell it, ie. keep a reference to them.

Upvotes: 7

Related Questions