Java Package

To better organize classes, Java provides a package mechanism to differentiate namespaces for class names.

The Role of Packages

  • 1. Organize classes or interfaces with similar or related functions into the same package to make it easy to find and use classes.

  • 2. Like folders, packages also use a tree-shaped directory storage method. Class names within the same package are different, and class names from different packages can be the same. When calling classes with the same name from two different packages at the same time, the package name should be added to distinguish them. Therefore, packages can avoid name conflicts.

  • 3. Packages also define access permissions. Only classes with package access permission can access classes in a particular package.

Java uses the package mechanism to prevent naming conflicts, control access, and provide search and location of classes, interfaces, enumerations, and annotations.

The syntax of the package statement is:

package pkg1[.pkg2[.pkg3…]];

For example, a Something.java file with the following content:

package net.java.util; public class Something{ ... }

Then its path should be:net/java/util/Something.javasaved in this way. The package is used to classify and store different Java programs, making it more convenient for other Java programs to call them.

A package can be defined as a group of interrelated types (classes, interfaces, enumerations, and annotations), providing access protection and namespace management for these types.

The following are some packages in Java:

  • java.lang- Packages for basic classes
  • java.io- Packages containing input/output functionality

Developers can package a group of classes and interfaces themselves and define their own packages. This is worth advocating in actual development. After you complete the implementation of classes, grouping related classes makes it easier for other programmers to identify which classes, interfaces, enumerations, and annotations are related.

Because a package creates a new namespace, it will not cause naming conflicts with any names in other packages. Using the package mechanism makes it easier to implement access control and simpler to locate related classes.


Creating Packages

When creating a package, you need to choose a suitable name for it. After that, if another source file contains classes, interfaces, enumerations, or annotation types provided by this package, the package declaration must be placed at the beginning of that source file.

The package declaration should be on the first line of the source file. Each source file can have only one package declaration, and every type in this file applies to it.

If a source file does not use a package declaration, then the classes, functions, enumerations, annotations, and so on in it will be placed in an unnamed package.

Examples

Let's look at an example. This example creates a package called animals. Usually lowercase letters are used for naming to avoid conflicts with class and interface names.

Add an interface to the animals package:

Animal.java file code:

/*Filename: Animal.java*/ package animals; interface Animal { public void eat(); public void travel(); }

Next, add the implementation of this interface in the same package:

MammalInt.java file code:

package animals; /*Filename: MammalInt.java*/ public class MammalInt implements Animal{ public void eat(){ System.out.println("Mammal eats"); } public void travel(){ System.out.println("Mammal travels"); } public int noOfLegs(){ return 0; } public static void main(String args[]){ MammalInt m = new MammalInt(); m.eat(); m.travel(); } }

Then, compile these two files and place them in a subdirectory called animals. Use the following command to run:

$ mkdir animals
$ cp Animal.class  MammalInt.class animals
$ java animals/MammalInt
Mammal eats
Mammal travel

The import keyword

In order to use the members of a package, we need to explicitly import that package in the Java program.

In Java,importthe keyword is used to import types defined in other classes or packages, so that these types can be used in the current source file.

importThe keyword is used to import classes, interfaces, or static members from other packages. It allows you to directly use classes from other packages in your code without fully specifying the class's package name.

In a Java source file, the import statement must be at the top of the Java source file. Its syntax is:

import package1[.package2…].(classname|*);

The import statement is placed after the package statement:

//The first non-comment line is the package statement. package com.example; //The import statement imports classes from other packages. import java.util.ArrayList; import java.util.List; //Class definition public class MyClass { //Class members and methods }

If a class in a package wants to use another class in the same package, the package name can be omitted.

You can use the import statement to import a specific class:

import com.example.MyClass;

In this way, you can directly use the methods, variables, or constants of the MyClass class in the current source file.

You can also use the wildcard*to import an entire package or subpackage:

import com.example.mypackage.*;

In this way, you can importcom.example.mypackageall classes in a package, so that you can use the methods, variables, or constants of any class in that package in the current source file. Note that when using the wildcard*to import an entire package, only the classes in the package are imported, not the subpackages of the package.

When importing a class or package, you need to provide the fully qualified name of the class or package. The fully qualified name includes the combination of package name and class name, with a dot.as the separator.

Examples

import java.util.ArrayList; // Import the ArrayList class from the java.util package
import java.util.*; // Import all classes from the java.util package

import com.example.MyClass; // Import the MyClass class from the com.example package
import com.example.*; // Import all classes from the com.example package

Example

The payroll package below already contains the Employee class. Next, we add a Boss class to the payroll package. When the Boss class references the Employee class, it does not need to use the payroll prefix. The Boss class example is as follows.

Boss.java file code:

package payroll; public class Boss { public void payEmployee(Employee e) { e.mailCheck(); } }

What if the Boss class is not in the payroll package? The Boss class must use one of the following methods to reference classes from other packages.

Use the fully qualified class name, for example:

payroll.Employee

useimportUse the keyword to import, using the wildcard*:

import payroll.*;

Useimportthe keyword to import the Employee class:

import payroll.Employee;

Note:

A class file can contain any number of import declarations. Import declarations must be after the package declaration and before the class declaration.


Directory Structure of Packages

Putting classes in packages has two main results:

  • The package name becomes part of the class name, as discussed earlier.
  • The package name must match the directory structure where the corresponding bytecode resides.

Here is a simple way to manage your own Java files:

Place the source code of types such as classes and interfaces in a text file. The name of the file is the name of the type, with .java as the extension. For example:

//Filename: Car.java package vehicle; public class Car { //Class implementation }

Next, place the source file in a directory that corresponds to the name of the class's package.

....\vehicle\Car.java

Now, the correct class name and path will look like this:

  • Class name -> vehicle.Car

  • Path name -> vehicle\Car.java (on Windows systems)

Usually, a company uses the reversed form of its internet domain name as its package name. For example, if the internet domain is example.com, all package names begin with com.example. Each part of the package name corresponds to a subdirectory.

For example, there is acom.example.testpackage that contains a source file named Example.java. Accordingly, there should be a series of subdirectories as follows:

....\com\example\test\Example.java

When compiling, the compiler creates a different output file for each type such as a class or interface defined in the package. The output file's name is the name of the type, with .class as the extension. For example:

//Filename: Example.java package com.example.test; public class Example { } class Google { }

Now, let's compile this file with the -d option, as follows:

$javac -d . Example.java

This will place the compiled files as shown below:

.\com\example\test\Example.class
.\com\example\test\Google.class

You can import all \com\example\test\ classes, interfaces, etc. defined in:

import com.example.test.*;

The compiled .class files should be placed, like the .java source files, in directories that correspond to the package name. However, it is not required that the path of the .class file be the same as the path of the corresponding .java file. You can arrange the source and class directories separately.

<path-one>\sources\com\example\test\Example.java
<path-two>\classes\com\example\test\Google.class

This way, you can share your class directory with other programmers without revealing your source code. Managing source code and class files in this way allows the compiler and the Java Virtual Machine (JVM) to find all types used in your program.

The absolute path of the class directory is calledclass pathSet in the system variableCLASSPATHThe compiler and the Java Virtual Machine construct the path of .class files by appending the package name to the class path.

<path- two>\classes is the class path, the package name is com.example.test, and the compiler and JVM will look for .class files in <path-two>\classes\com\example\test.

A class path may contain several paths. Multiple paths should be separated by a delimiter. By default, the compiler and JVM look in the current directory. JAR files contain Java platform-related classes, so their directories are placed in the class path by default.


Setting the CLASSPATH System Variable

Use the following command to display the current CLASSPATH variable:

  • Windows platform (DOS command line): C:\> set CLASSPATH
  • UNIX platform (under Bourne shell): # echo $CLASSPATH
Clear the current CLASSPATH variable content:
  • Windows platform (DOS command line): C:\> set CLASSPATH=
  • UNIX platform (under Bourne shell): # unset CLASSPATH; export CLASSPATH

Set the CLASSPATH variable:

  • Windows platform (DOS command line): C:\> set CLASSPATH=C:\users\jack\java\classes
  • UNIX platform (under Bourne shell): # CLASSPATH=/home/jack/java/classes; export CLASSPATH
Other extensions