To better organize classes, Java provides a package mechanism to distinguish the namespaces of class names.
Purpose of Packages
- 1. Organize classes or interfaces with similar or related functions into the same package, making it easier to find and use classes.
- 2. Similar to folders, packages also use a tree directory structure. Class names within the same package are unique, while class names in different packages can be the same. When calling classes with the same name from two different packages, the package name should be added to distinguish them. Therefore, packages can avoid name conflicts.
- 3. Packages also restrict access permissions; only classes with package access permission can access classes in a certain package.
Java uses the package mechanism to prevent naming conflicts, control access, and provide search and locate classes, interfaces, enumerations, and annotations.
The syntax for the package statement is:
package pkg1[.pkg2[.pkg3...]];
For example, a file named Something.java with the content:
package net.java.util;
public class Something {
...
}
Then its path should be saved as net/java/util/Something.java. The purpose of packages is to categorize and store different Java programs, making them easier to be called by other Java programs.
A package can be defined as a set of related types (classes, interfaces, enumerations, and annotations), providing access protection and namespace management for these types.
Here are some packages in Java:
- java.lang - Packages basic classes.
- java.io - Contains functions for input and output.
Developers can package a set of classes and interfaces themselves and define their own packages. In actual development, this is encouraged. After you complete the implementation of a class, grouping related classes makes it easier for other programmers to determine which classes, interfaces, enumerations, and annotations are related.
Since packages create a new namespace, there will be no naming conflicts with any names in other packages. Using the package mechanism makes it easier to implement access control and simplifies locating related classes.
Creating Packages
When creating a package, you need to give it a suitable name. 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 only have one package declaration, and every type in this file applies to it.
If a source file does not use a package declaration, then its classes, functions, enumerations, annotations, etc., will be placed in an unnamed package.
Example
Let's look at an example that creates a package called animals. Typically, 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:
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;
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 commands to run:
$ mkdir animals
$ cp Animal.class MammalInt.class animals
$ java animals/MammalInt
Mammal eats
Mammal travels
The import Keyword
To use members of a package, we need to explicitly import that package in the Java program.
In Java, the import keyword is used to import types defined in other classes or packages so that these types can be used in the current source file.
The import keyword is used to bring in classes, interfaces, or static members from other packages. It allows you to directly use classes from other packages in your code without needing to specify the full package name of the class.
In a Java source file, the import statement must be located at the top of the file. Its syntax is:
import package1[.package2...].(classname|*);
The import statement is placed after the package statement:
package com.example;
import java.util.ArrayList;
import java.util.List;
public class MyClass {
...
}
If a class in a package wants to use another class in the same package, the package name can be omitted.
You can use an import statement to import a specific class:
import com.tutorial.MyClass;
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 sub-packages of a package:
import com.tutorial.mypackage.*;
This allows you to import all classes in the com.tutorial.mypackage package, so 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 sub-packages.
When importing classes or packages, you need to provide the fully qualified name of the class or the fully qualified name of the package. The fully qualified name includes the combination of the package name and the class name, separated by a dot ..
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 following payroll package already contains the Employee class. Now, 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 instance of the Boss class 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 in other packages.
Use the full class name, for example:
payroll.Employee
Use the import keyword with the wildcard *:
import payroll.*;
Use the import keyword to import the Employee class:
import payroll.Employee;
Note:
A class file can contain any number of import declarations. The import declaration must be after the package declaration and before the class declaration.
Package Directory Structure
Placing classes in packages has two main consequences:
- The package name becomes part of the class name, as we discussed earlier.
- The package name must match the directory structure where the corresponding bytecode is located.
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 file name is the name of the type, with a .java extension. For example:
package vehicle;
public class Car {
...
}
Next, place the source file in a directory that corresponds to the package name of the class.
....vehicleCar.java
Now, the correct class name and path should look like this:
- Class name ->
vehicle.Car - Path name ->
vehicleCar.java(on Windows systems)
Typically, 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 start with com.tutorial. Each part of the package name corresponds to a subdirectory.
For example: there is a package com.tutorial.test, which contains a source file named Tutorial.java. Then, there should be a corresponding series of subdirectories like this:
....comtutorialtestTutorial.java
When compiling, the compiler creates a different output file for each class, interface, etc., defined in the package. The output file name is the name of the type, with a .class extension. For example:
package com.tutorial.test;
public class Tutorial {
...
}
class Google {
...
}
Now, we compile this file using the -d option, as follows:
$ javac -d . Tutorial.java
This will place the compiled files as follows:
.comtutorialtestTutorial.class
.comtutorialtestGoogle.class
You can import all classes, interfaces, etc., defined in comtutorialtest like this:
import com.tutorial.test.*;
The compiled .class files should be placed in directories that correspond to the package name, just like the .java source files. However, it is not required that the path of the .class file be the same as the corresponding .java path. You can arrange the source code and class directories separately.
sourcescomtutorialtestTutorial.java
classescomtutorialtestGoogle.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 the types used in your program.
The absolute path of the class directory is called the class path. It is set in the system variable CLASSPATH. The compiler and the JVM construct the path to the .class file by adding the package name to the class path.
If classes is the class path and the package name is com.tutorial.test, then the compiler and JVM will look for the .class file in classescomtutorialtest.
A class path may contain multiple paths, which should be separated by a separator. By default, the compiler and JVM look in the current directory. JAR files contain classes related to the Java platform, so their directories are included in the class path by default.
Setting the CLASSPATH System Variable
Use the following commands to display the current CLASSPATH variable:
- Windows platform (DOS command line):
C:> set CLASSPATH - UNIX platform (Bourne shell):
# echo $CLASSPATH
Delete the current CLASSPATH variable content:
- Windows platform (DOS command line):
C:> set CLASSPATH= - UNIX platform (Bourne shell):
# unset CLASSPATH; export CLASSPATH
Set the CLASSPATH variable:
- Windows platform (DOS command line):
C:> set CLASSPATH=C:usersjackjavaclasses - UNIX platform (Bourne shell):
# CLASSPATH=/home/jack/java/classes; export CLASSPATH
YouTip