Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there any advantage of adding a inner class over a java class in a new file? [duplicate]

Tags:

java

I would like to know if there any advantage of adding an inner class over a java class in a new file. Assuming these are only the two ways i can achieve that is needed. But I would only like to which one is a better approach of these two.

class ABC{ 
  LMN obj;
   public static class xyz{
     @customAnnotation LMN lmn; 
     public void set(ABC abc){
      abc.obj = lmn;
     }
   }
}

or have a separate class like this

public class xyz{
     @customAnnotation LMN lmn;
     public void set(ABC abc){
      abc.obj = lmn;
     }
}
like image 719
Nishant Avatar asked Jan 27 '23 22:01

Nishant


2 Answers

This is mainly a question of design.

From the JAVA SE Docs:

Why Use Nested Classes?

It is a way of logically grouping classes that are only used in one place: If a class is useful to only one other class, then it is logical to embed it in that class and keep the two together. Nesting such "helper classes" makes their package more streamlined.

Meaning if you only need to create and use instances of the class xyz within the context of the class ABC, then it makes sense for you to define it as an inner class inside ABC.

Doing so hides the inner class from the outside world, and gives the outer class access to its private data members (generally speaking, read more below). This makes your code easier to read and easier to understand, but more importantly it increases encapsulation and data hiding - ensuring the class is only visible to and accessible by those who need to use it. This is a fundamental principle in Object Oriented Programming.


On a more practical note:

There are two different types of nested classes in Java: static and non-static. Each type defines a different access-privileges relationship with its defining outer class. You can read more about the differences here.

like image 85
yuvgin Avatar answered Feb 15 '23 22:02

yuvgin


There are a few advantages, most of which are access control-related:

  1. Unless this was included inadvertently in your question, the first advantage is right in your post (package-private access). ABC being package-private, ABC.xyz cannot be statically referenced outside the package. So a nested class allows for better access control (xyz can even be private or protected).
  2. ABC.xyz can access private ABC members (static ones), which removes the need for exposing encapsulated fields to the world if accessing them from xyz is required
  3. Regarding readability, a nested class makes coupling obvious (assuming it is right)
like image 45
ernest_k Avatar answered Feb 16 '23 00:02

ernest_k