Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Benefit of using Nested class in java

what are the benefits of using nested class in Java? In many examples it seems to me it only adds complexity to the design. Is there any example that shows the power of using nested class in comparison to for example composite pattern?

like image 773
Reza Avatar asked Jan 08 '13 16:01

Reza


People also ask

What is nested class advantage?

Nested classes are used to develop more readable and maintainable code because it logically group classes and interfaces in one place only. Code Optimization: It requires less code to write.

Is it good practice to use nested classes?

Nested Class can be used whenever you want to create more than once instance of the class or whenever you want to make that type more available. Nested Class increases the encapsulations as well as it will lead to more readable and maintainable code.

What are two advantages to using inner classes?

It requires less code to write. It has nested classes which are used to develop more readable and maintainable code. It logically group classes and interfaces in one place only. It can access all the members (data members and methods) of outer class including private.

Does nested classes increase encapsulation?

There are several compelling reasons for using nested classes, among them: It is a way of logically grouping classes that are only used in one place. It increases encapsulation. Nested classes can lead to more readable and maintainable code.


1 Answers

Why Use Nested Classes?

There are several compelling reasons for using nested classes, among them:

  • It is a way of logically grouping classes that are only used in one place.
  • It increases encapsulation.
  • Nested classes can lead to more readable and maintainable code.

(from the docs)

I think that the best case I can think of, off the top of my head would be the implementation of nodes in some sort of collection class (tree, linked list, map, etc). There is no reason why the node implementation should be exposed to the public, and since it is only used by the internals of your collection, it makes sense to make the node class nested inside the collection class.

Something along the lines of..

public class MyTree {
  private class TreeNode {
    //implementation details...
  }

  //public api, where implementation references TreeNode
}
like image 175
Dylan Avatar answered Sep 18 '22 16:09

Dylan