Java SE – Packages

An understanding of packages was part of the requirements of becoming an Oracle Certified Java Programmer. Here I’ll cover what packages mean.

A source folder
When compiling Java the folders and packages must match, e.g. a class called com.vff.Runner would need to be in a folder called vff inside another folder called com. If the class is public it needs to be in a file called On windows it would be com\vff\ and Unix/Linux would be com/vff/

A logical grouping of classes
An example would be if we were writing a program called mycrm for a company called bling. Imagine if we had the following classes: CustomerService, CustomerValidator, ValidationRule, Customer, CustomerAddress, CustomerContact and a CustomerDatabaseWriter. We could try to group these with the following package and classnames:
package: com.bling.mycrm.service classes: CustomerService
package: com.bling.mycrm.validation classes: CustomerValidator, ValidationRule
package: com.bling.mycrm.model classes: Customer, CustomerAddress, CustomerContact
package: com.bling.mycrm.database classes: CustomerDatabaseWriter.

A way of limiting access to other classes methods
Imagine that the ValidationRule instances should only be visible to other Validation classes, i.e. CustomerValidator. We can enforce this by giving the class default visibility. By not making it protected, private or public only other classes in the same package (com.bling.mycrm.validation) can see it. Alternatively we could make methods of the rule have default visibility with the same technique.

In some other languages packages are referred to as namespaces.

When a class refers to other classes in the same package, or in the special java.lang package, the class referred to does not need its package specified (or to be imported).

There is a more extensive explanation of concepts on wikipedia here: