官术网_书友最值得收藏!

Packages

Classes are organized into packages and the first code line in a file should specify the package that the class is in.

package packt.java9.by.example.stringsort;

If you do not specify the package, then the class will be in the default package. This should not be used, except in the simplest case when you want to try some code. With Java 9, you can use jshell for this purpose, so, as opposed to previous versions of Java, now the suggestion becomes very simple—never put any class in the default package.

The name of the packages is hierarchical. The parts of the names are separated by dots. Using package names helps you avoid name collisions. Names of the classes are usually kept short and putting them into packages helps the organization of the program. The full name of a class includes the name of the package the class is in. Usually, we will put those classes into a package that are in some way related, and add something to a similar aspect of a program. For example, controllers in an MVC pattern program are kept in a single package. Packages also help you avoid name collision of classes. However, this only pushes the problem from class name collision to package name collision. We have to make sure that the name of the package is unique and does not cause any problem when our code is used together with any other library. When an application is developed, we just cannot know what other libraries will be used in later versions. To be prepared for the unexpected, the convention is to name the packages according to some Internet domain names. When a development company has the domain name acmecompany.com, then their software is usually under the com.acmecompany...  packages. It is not a strict language requirement. It is only a convention to write the domain name from right to left, and use it as package name, but this proves to be fairly good in practice. Sometimes, like I do in this book, one can deviate from this practice so you can see that this rule is not carved in stone.

When the rubber hits the road, and the code is compiled into byte code, the package becomes the name of the class. Thus, the full name of the Sort class is packt.java9.by.example.stringsort.Sort. When you use a class from another package, you can use this full name or import the class into your class. Again, this is on the language level. Using the fully qualified name or importing makes no difference when Java becomes byte code.

主站蜘蛛池模板: 资阳市| 邵阳市| 盐城市| 梅州市| 文成县| 庆云县| 图木舒克市| 西和县| 成都市| 平陆县| 绵竹市| 左云县| 仪陇县| 呈贡县| 漳州市| 博客| 新蔡县| 印江| 景德镇市| 广饶县| 同江市| 寿宁县| 武清区| 太湖县| 稻城县| 塔河县| 望江县| 四平市| 安顺市| 筠连县| 克山县| 陈巴尔虎旗| 清水河县| 临朐县| 彭泽县| 鄂尔多斯市| 玉龙| 万源市| 怀仁县| 罗平县| 鹤岗市|