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;
}
}
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.
There are a few advantages, most of which are access control-related:
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
).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 requiredIf 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