Why do we declare nested public static classes in java, even though it is used somewhere else?
I’m going through the legacy codebase and observing that they use the public static
class in the outer class, and the nested public static class is not only used in the outer class, but it is used in many other classes (classes)?
What are the design decisions behind this? If it is also used externally, then why wasn’t it itself created as a separate public class in the first place?
So in my example, it looks like this: –
public class OuterNestedClass {
private int a;
private List<InnerClass> innerClasses;
public static class InnerClass {
private int b;
public InnerClass(int b) {
this.b = b;
}
public void show(){
System.out.println("Value of b "+b);
}
}
}
Other classes that use innerclass
are as follows: –
public class OutsideClass {
public static void main(String[] args) {
OuterNestedClass.InnerClass innerClass = new OuterNestedClass.InnerClass(10);
innerClass.show();
}
}
Let me know if you need any instructions.
Solution
The main reason is namespaces. Static classes are utility classes, and they tend to become very large. Nested classes allow you to break utilities nicely while still keeping everything together.
So instead of having 20 methods, you might have 5 Utils.Password and 15 Utils.Json
The best example I’ve seen is how Retrofit.Builder is done:
https://github.com/square/retrofit/blob/master/retrofit/src/main/java/retrofit2/Retrofit.java#L394