Declaring Packages

Packages allow grouping of related types (classes, interfaces, etc) while providing access protection and namespace management.

The package declaration must be the first statement at the top of every source file that contains the types that you want to include in the package.

The recommended naming convention is:

  • All lower case (no camelCase)
  • Reverse domain names
  • Underscores to replace illegal Java naming characters

The following is an example of a package declaration:

Importing Packages

You import a package from a source file to access its accessible members. It’s possible to import entire packages or just specific package members:

  • Import all the package members: import com.acme.foo.*;
  • Import a package member: import acme.foo.A;
  • Import a class members: import com.acme.foo.A.*;

In addition, the Java compiler always automatically imports two entire packages for every source file:

  • java.lang package
  • The current package

Remember that packages provide namespaces and no hierarchies: import com.acme.*; doesn’t import classes in package com.acme.foo.

Finally, it’s also possible to access other package members without importing them by using their fully qualified names: new com.acme.foo.A();.

Static Import

Thes static import feature of Java avoids the need to prefix the class name to use static members:

Be careful: although this feature is called static import, the right order of the Java keywords is import static and this sometimes leads to misunderstanding.

The Java classpath

The classpath is a Java property that tells the compiler and the virtual machine where to look for class files (a list of directories and jar files).

If the classes are grouped into packages, there must be an equivalent directory hierarchy inside the specified directories or jar files.

By default the following locations are always automatically added to the classpath:

  1. The current directory (where the compiler or virtual machine is executed)
  2. The jar file containing the Java platform classes

 


Leave a Reply