I have many objects of type ContainedClass stored in an object of type ContainingClass . I need to access a container object from internal objects. At the moment, I am doing this by passing a reference to the container object in the constructor of other objects, such as ContainedClass cclass = new ContainedClass(this); and saving it as a ContainingClass owner .
It seems ugly to me, and a solution that seems appropriate to me uses inner classes, but the definition of ContainedClass is very large and seems inappropriate. So what options should I go with? Or is there another obvious option that I'm missing?
Here is a code snippet of the code that I found on the Internet, depicting what I will use for inner classes.
public class TestIt { public static void main(String a[]){ new TestIt().doit(); } 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 another advantage of the inner classes that I was looking at was that a ContainedClass can only exist in a ContainerClass , which is the desired result.
Kyle source share