Reputation:
I was going through the legacy code base and observed that so many places they are using the public static
class inside an outer class and nested public static class is not just being used in the outer class but its being used in so many other class?
What would be the design decision behind that and if it being used outside as well then why it wasn't created as a standalone public class in the first place itself.
So in my example it looks like below :-
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);
}
}
}
And other class which uses the innerclass
looks like below :-
public class OutsideClass {
public static void main(String[] args) {
OuterNestedClass.InnerClass innerClass = new OuterNestedClass.InnerClass(10);
innerClass.show();
}
}
Let me know if any clarification is required.
Upvotes: 3
Views: 88
Reputation: 17691
Main reason for that would be namespacing. Static classes are utility classes, and those tend to grow very large. Nested classes let you break your utilities nicely, while still keeping everything together.
So, instead of having Utils with 20 methods, you probably have Utils.Password with 5 and Utils.Json with 15
Best example for that I've seen is how Retrofit.Builder is done: https://github.com/square/retrofit/blob/master/retrofit/src/main/java/retrofit2/Retrofit.java#L394
Upvotes: 3