[英]Why we declare the nested public static class in java, even though its being used in some other places as well?
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? 我正在浏览遗留代码库并观察到很多地方他们在外部类中使用public static
类,而嵌套的公共静态类不只是在外部类中使用,而是在其他许多类中使用它?
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 :- 使用innerclass
类的其他类如下所示: -
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. 如果需要澄清,请告诉我。
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 因此,您可能拥有带有5的Utils.Password和带有15的Utils.Json,而不是使用带有20种方法的Utils
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 我见过的最好的例子是Retrofit.Builder是如何完成的: https : //github.com/square/retrofit/blob/master/retrofit/src/main/java/retrofit2/Retrofit.java#L394
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.