I was reading nested classes will enable group classes & interfaces logically.
I feel this we can achieve using package as well by placing related classes in a package.
If this is the case, where exactly the Nested class and Nested interface come into play? When should we consider using them?
There is one main thing that you can do with nested classes/interfaces, that you cannot do with packages: You can have types that are private to a specific class. Standalone interfaces and classes can only be public or have the default (package-wide) visibility. This can be quite helpful if you wish to limit the access to the internals of an implementation.
In addition, non-static nested classes will contain an implicit reference to the parent object. This reduces the amount of code that you need to write - no need for parameterized new MyObject(this) constructor calls - although it may also increase the size of a type inadvertently if the parent object field is not used.
I would say that to a degree the use of inner classes is a matter of design and personal preference. For example, in my own projects I often choose to split-off an inner type to a separate file when its code becomes too large for my tastes. In public objects, however, the need to hide the details of an implementation may be more important.
PS: By the way, the Java compiler creates a separate class file for each type anyway - from the POV of the JVM whatever you do is mostly the same...
Let's look at a grouping.
class Container {
public class Item {
... can use Container.this to access its container.
}
private List<Item> items = ...;
public Item createNewItem() {
Item item = new Item();
items.add(item);
return item;
}
}
The interesting design offers to every Item the access to the Container it is in.
The same mechanism is used in standard java SE with Iterator implementations. The implementation class often is an embedded class of the collection, thus having access to it.
I do not know the context of your citation, but that might be what was meant.
This pattern allows access to private members of the containing class, and the alternative would need an extra constructor argument to maintain a link to the containing object.
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