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:
1 2 3 |
package com.company.project.packagename; |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
// importing a constant import static java.lang.Math.PI; … double p = PI; // importing a static method import static java.lang.Math.round; … double r = round(1.5); // importing all the static members of a class import static java.lang.Math.*; … double r = cos(PI * theta); |
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
:
- The current directory (where the compiler or virtual machine is executed)
- The
jar
file containing the Java platform classes