Non-public top-level class vs static nested class

女生的网名这么多〃 提交于 2019-11-27 12:59:01

问题


It seems to me that non-public top-level classes and static nested classes essentially perform the same tasks when creating a helper class.


A.java


public class A 
{
    public static main (String[] args)
    {
        AHelper helper = new AHelper();     
    }
}
class AHelper {}


A.java


public class A
{
    public static main (String[] args)
    {
        A.AHelper helper = new A.AHelper();     
    }

   static class AHelper {}
}


Aside from how they are referenced, there seems to me very little difference between the two ways of creating a helper class. It probably comes down mostly to preference; does anyone see anything I'm missing? I suppose some people would argue that it's better to have one class per source file, but from my perspective it seems cleaner and more organized to have a non-public top-level class in the same source file.


回答1:


In neither example do you have one class per source file. But generally, you use a static nested class to signify that it is only intended to be used within its enclosing class (forcing it to be referenced as A.AHelper). That is not so clear if you move that class to the top level.

From the Sun tutorial:

Logical grouping of classes—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.




回答2:


One thing that comes to mind is the scope of the helper class. A nested class has access to private members of the parent class. If the helper is in its own file, you don't enjoy such access, although it is easy to handle with the default package visible scope.

Another consideration is code reuse - you might want your helper to help several classes in your package.




回答3:


One difference is that a static nested class can be declared public. You cannot do this for any other class in the same file as the primary class as a public main level class must be the same name as the file name.

So you could declare many public classes in one file, but only one of them being the main level. The other static nested classes ought to be related though to the main class or it really does not make sense to do that.




回答4:


Nesting a class (statically in Java) sends a clear message of intent: the nested class AHelper is only relevant and usable to support A class. It has no meaning on its own, and this is immediately obvious.



来源:https://stackoverflow.com/questions/2148686/non-public-top-level-class-vs-static-nested-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!