In response to your comment (it would be unreadable if I posted it in the comments) where it belongs. An example of using the inner class outside the outer.
public class Dog { String name; } public class HugeKennel { Double[] memmoryWaste = new Double[10000000]; public List<Dog> getDogs() { SneakyDog trouble = new SneakyDog("trouble"); return Arrays.asList(trouble); } class SneakyDog extends Dog { SneakyDog(String name) { this.name = name; } } }
somewhere else in your code
List<Dog> getCityDogs() { List<Dog> dogs = new ArrayList<>(); HugeKennel k1 = ... dogs.addAll(k1.getDogs()); HugeKennel k2 = ... dogs.addAll(k2.getDogs()); return dogs; } .... List<Dog> cityDogs = getCityDogs(); for (Dog dog: dogs) { walkTheDog(dog); }
Thus, you do not need to access the inner class through its parrent class, as soon as the inner object is created, it can be used like any other object and can be "leaked out" into its container class, as in the example above, when the list of dogs will be contain links to dogs, but each dog still "knows" about its kennel.
A related example from StackTrace was related to a typical use case when inner classes are created as "anonymous inner classes", but this is the same problem. If you pass a reference to any instance of the inner class, you also pass the reference to the outer class.
Zielu source share