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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.186.143