top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Java: Why should we use nested classes? Has it any benefit? Can someone show me cases from real life?

+2 votes
473 views
Java: Why should we use nested classes? Has it any benefit? Can someone show me cases from real life?
posted Feb 9, 2015 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

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.

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
}
answer Feb 27, 2015 by Amit Kumar Pandey
...