I have a lot of objects of type ContainedClass
stored in an object of type ContainingClass
. I need to access the container object from the inside objects. As of now I am doing this by passing a reference to the container object in the constructor of the other objects like ContainedClass cclass = new ContainedClass(this);
and storing it as ContainingClass owner
.
This seems ugly to me, and the solution that seems fitting to me is using inner classes, but the definition for ContainedClass is very large and that seems to be inappropriate. So which of the options should I go with? Or is there another obvious option I'm missing?
Here is a piece of sample code I found online depicting what I'd be going for using inner classes.
public class TestIt {
public static void main(String a[]){
new TestIt().doit();
/*
output :
Hello world!
*/
}
public void doit() {
new InnerClass().sayHello();
}
public void enclosingClassMethod(){
System.out.println("Hello world!");
}
class InnerClass {
public void sayHello() {
TestIt.this.enclosingClassMethod();
}
}
}
I should add that the other benefit of inner classes I was looking at was that ContainedClass
could only exist in ContainerClass
, which is a desired outcome.