非公共顶级类vs静态嵌套类 [英] Non-public top-level class vs static nested class

查看:133
本文介绍了非公共顶级类vs静态嵌套类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我看来,非公共顶级类和静态嵌套类在创建帮助器类时基本上执行相同的任务。

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


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


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.

推荐答案

在两个示例中,每个源文件都有一个类。但通常,您使用静态嵌套类来表示它仅用于在其封闭类中使用(强制它被引用为 A.AHelper )。如果你把那个班级提升到最高水平,那就不那么清楚了。

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.

来自 Sun教程


类的逻辑分组 - 如果一个
类只对另一个类有用,那么
则将它嵌入到
类中是合乎逻辑的,并将两者保持在一起。
嵌套这样的助手类会使
的包更加精简。

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.

这篇关于非公共顶级类vs静态嵌套类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆