Non-public top level class in Java

前端 未结 5 427
自闭症患者
自闭症患者 2021-01-03 03:28

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

Let\'s say we have Foo.java, there could be

class Foo {
}
5条回答
  •  没有蜡笔的小新
    2021-01-03 04:09

    It is considered good design to keep the visibility of a class to the most minimum required. The reasons that I can think of:

    1. The class can easily change in the future without causing breakages in external packages as the external packages do not have access to the class. In this regard it might be even better to start off a class by making it a private inner class.
    2. The class being package visible cannot be extended by classes in external packages. This again makes it easier for this class to change without causing breaking changes in external packages. If this class was not meant to be extended then it would be even better to make this final.
    3. A public visible class becomes a part of the exported API of your library. If you are a library designer, it is better to keep your exported API as small as possible because you do not want to confuse your consumer with un-necessary classes/details. Item 1 would again hold good in this case.

    The book "Effective Java" by Josh Bloch is an excellent reference for Idiomatic Java code and design.

提交回复
热议问题