Java中的非公共顶级类 [英] Non-public top level class in Java

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

问题描述

在Java中创建顶级类非公共的原因是什么?

What's the reason of making top-level class non-public in Java?

假设我们有 Foo.java ,可能有

class Foo {
}

public class Foo {
}

我知道前一个例子会有一些类 - 可见性问题(可能它赢了)从其他包装中可以看到)。但无论如何,有没有理由为什么有人会像第一个代码样本那样做?

I understand that there will be some class - visibility issues with the former example (probably it won't be visible from other packages). But anyway, are there any reasons why someone may want to do as in the first code sample?

UPD:我在前一个解决方案中看到的有什么缺点:没有人关心它是什么非公开。该类可以稍后在同一个包中通过其他一些 public 类进行扩展,然后,该类的非公共部分可能会为您带来可见性/访问问题。

UPD: What cons I see in the former solution: nobody cares that it's non-public. That class can be simply extended by some other public class in the same package later, then, non-public part of the class may bring you visibility/access issues.

推荐答案

这是一个例子。
没有人需要知道我们的ConcreteDocument是否存在。

Here is an example. No one needs to know about existence of our ConcreteDocument.

public interface DocumentIF {
}



ConcreteDocument.java



ConcreteDocument.java

class ConcreteDocument implements DocumentIF {
}



DocumentFactory.java



DocumentFactory.java

public class DocumentFactory {
    public DocumentIF createDocument() {
        return new ConcreteDocument();
    }
}

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

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