Introduction to JVM Languages
上QQ阅读APP看书,第一时间看更新

What are packages?

Most languages covered in this book support grouping classes in packages. Classes that are grouped inside a package form a unique namespace. This is the fundamental feature of a JVM. Some languages cannot group classes in a package themselves, but they still support referencing classes inside a package.

An example is Oracle's Nashorn JavaScript interpreter. The JavaScript language itself does not support packages, but Nashorn can still import existing Java (or compatible) classes that are put in packages.

To demonstrate how classes can be organized in a package, let's look at an implementation of a basket in an e-commerce application again, but this time a little bit more developed example than the previous time.

JVM offers a way to organize classes by placing them in packages. By doing this, classes with the same theme can be grouped together. In the example illustrated just now, it would make sense to group classes in the following packages:

I chose this organization because I consider basket, product, and user as the main themes of these classes. Also, I expect that the Basket, Product, and User classes will be used by several other classes in future, and the BasketLine class will only be used internally by the Basket class.

Packages not only make the structure of larger projects easier to understand, as we will see shortly, but also hide class members from classes in other packages, using access modifiers.

To make efficient usage of packages, you should understand the convention that almost all major JVM projects follow. Although package names, as chosen in the preceding table, are perfectly valid, there's a convention that is recommended when naming packages.