Kris Nuttycombe
Kris Nuttycombe

Reputation: 4580

How to refer to the outer class in another instance of a non-static inner class?

I'm using the Apache Commons EqualsBuilder to build the equals method for a non-static Java inner class. For example:

import org.apache.commons.lang.builder.EqualsBuilder;

public class Foo {
    public class Bar {
        private Bar() {}

        public Foo getMyFoo() {
            return Foo.this
        }

        private int myInt = 0;

        public boolean equals(Object o) {
            if (o == null || o.getClass() != getClass) return false;

            Bar other = (Bar) o;
            return new EqualsBuilder()
                .append(getMyFoo(), other.getMyFoo())
                .append(myInt, other.myInt)
                .isEquals();
        }
    }

    public Bar createBar(...) {
        //sensible implementation
    }

    public Bar createOtherBar(...) {
        //another implementation
    }

    public boolean equals(Object o) {
        //sensible equals implementation
    }
}

Is there syntax by which I can refer to other's Foo reference apart from declaring the getMyFoo() method? Something like other.Foo.this (which doesn't work)?

Upvotes: 14

Views: 4580

Answers (3)

Ray Tayek
Ray Tayek

Reputation: 10003

yes:

public class Foo {
    public class Bar {
        public Foo getMyFoo() {
            return Foo.this;
        }
    }
    public Foo foo(Bar bar) {
        return bar.getMyFoo();
     }
    public static void main(String[] arguments) {
        Foo foo1=new Foo();
        Bar bar1=foo1.new Bar();
        Foo foo=(new Foo()).foo(bar1);
        System.out.println(foo==foo1);
    }
}

Upvotes: -1

p3t0r
p3t0r

Reputation: 1980

No, not possible without a getter. The 'this' keyword will always point to the current instance. I'm quite curious why you would want to do this... seems like you are doing composition in the wrong way.

public class Foo {

  public Bar createBar(){
    Bar bar = new Bar(this)
    return bar;
  }
}

public class Bar {
  Foo foo;
  public Bar(Foo foo){
    this.foo = foo;
  }

  public boolean equals(Object other) {
    return foo.equals(other.foo);
  }
}

Since using Foo.this limits creation of the inner class (Foo myFoo = new Foo(); myFoo.new Bar(); to an instance I'd say this is much cleaner.

Upvotes: 2

Dave DiFranco
Dave DiFranco

Reputation: 1735

No.

The best way is probably what you suggested: add a getFoo() method to your inner class.

Upvotes: 6

Related Questions