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)?
To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax: OuterClass outerObject = new OuterClass(); OuterClass. InnerClass innerObject = outerObject.
Unlike inner class, a static nested class cannot access the member variables of the outer class. It is because the static nested class doesn't require you to create an instance of the outer class.
No inner class objects are automatically instantiated with an outer class object. If the inner class is static, then the static inner class can be instantiated without an outer class instance. Otherwise, the inner class object must be associated with an instance of the outer class.
Modifiers. You can use the same modifiers for inner classes that you use for other members of the outer class. For example, you can use the access specifiers private , public , and protected to restrict access to inner classes, just as you use them to restrict access do to other class members.
No.
The best way is probably what you suggested: add a getFoo() method to your inner class.
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.
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