English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Arrays

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List

Java Queue (Queue)

Java Map collection

Java Set collection

Java Input/Output (I/O)/O)

Java Reader/Writer

Other Java topics

Java Packages (package)

To better organize classes, Java provides a package mechanism to distinguish class names in the namespace.

The role of the package

  • 1Organize classes or interfaces with similar or related functions in the same package, which is convenient for searching and using classes.

  • 2Like folders, packages also adopt a tree directory storage method. The names of classes in the same package are different, and the names of classes in different packages can be the same. When calling classes with the same class name in two different packages at the same time, the package name should be added to distinguish them. Therefore, packages can avoid name conflicts.

  • 3The package also limits access privileges, and only classes with package access privileges can access classes in a certain package.

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

The syntax format of the package statement is:

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

For example, the content of a Something.java file

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

Then its path should be net/java/util/Something.java This is how it is saved. The role of package (package) is to classify and save different java programs, making it easier for other java programs to call them.

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

The following are some packages in Java:

  • java.lang-Pack the basic classes

  • java.io-Functions with input/output functionality

Developers can package a group of classes and interfaces themselves and define their own packages. In actual development, it is recommended to do so, as grouping related classes after completing the implementation of a class makes it easier for other programmers to determine which classes, interfaces, enumerations, and comments are related.

Since a package creates a new namespace (namespace), it will not conflict with any names in other packages. Using this package mechanism makes it easier to implement access control and simplifies the process of locating related classes.

Create a package

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

The package declaration should be on the first line of the source file, and each source file can only have one package declaration, which applies to all types in this file.

If a source file does not use a package declaration, then the classes, functions, enumerations, comments, and other elements within it will be placed in an unnamed package (unnamed package).

Instance

Let's look at an example, which creates a package called 'animals'. It is usually recommended to use lowercase letters for naming to avoid conflicts with class and interface names.

Add an interface (interface) to the 'animals' package:

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

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

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

import keyword

To be able to use a member of a certain package, we need to explicitly import that package in the Java program. The 'import' statement can accomplish this function.

In a Java source file, the import statements should be placed after the package statement and before all class definitions. They can be absent or multiple, and their syntax format is as follows:

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

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

Instance

The payroll package already contains the Employee class. Next, add a Boss class to the payroll package. When the Boss class refers to the Employee class, it does not need to use the payroll prefix. Here is an example of the Boss class.

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 refer to classes in other packages.

Using the full name of the class to describe, for example:

payroll.Employee

using import Keyword to introduce, using wildcard "*"

import payroll.*;

using import Keyword to introduce Employee class:

import payroll.Employee;

Note:

Class files can contain any number of import statements. Import statements must be placed after the package statement and before the class statement.

Package directory structure

There are two main results of placing classes in packages:

  • The package name becomes part of the class name, as discussed earlier.

  • The package name must match the directory structure where the corresponding bytecode is located.

Here is a simple way to manage your java files:

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

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

Next, place the source file in a directory that corresponds to the name of the package where the class is located.

....\vehicle\Car.java

Now, the correct class name and path will be as follows:

  • Class name -> vehicle.Car

  • Path name -> vehicle\Car.java (in Windows system)

Generally, a company uses the reversed form of its internet domain name as its package name. For example, the internet domain name is oldtoolbag.com, all package names end with com.w3codebox at the beginning. Each part of the package name corresponds to a subdirectory.

For example, there is a com.w3codebox.test This package contains a file named w3If the source file codebox.java is compiled, then correspondingly, there should be a series of subdirectories as follows:

....\com\w3codebox\test\w3codebox.java

When compiling, the compiler creates a different output file for each class, interface, and other types defined in the package, and the name of the output file is the name of the type, with .class as the file extension. For example:

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

Now, we use-d option to compile this file, as follows:

$javac -d . w3codebox.java

This will place the compiled files as follows:

.\com\w3codebox\test\w3codebox.class
.\com\w3codebox\test\Google.class

You can import all like this below \com\w3codebox\test\ Classes, interfaces, and other definitions defined in the following:

import com.w3codebox.test.*;

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

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

This allows you to 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 JVM to find all types used in your program.

The absolute path of the class directory is called class path. It is set in the system variable CLASSPATH In this way, the compiler and the Java virtual machine (JVM) construct the path of .class files by adding the package name to the class path.

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

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

Set CLASSPATH System Variable

Use the following command to display the current CLASSPATH variable:

  • Windows Platform (DOS Command Line): C:\> set CLASSPATH

  • UNIX Platform (Bourne shell): # echo $CLASSPATH

Delete Current CLASSPATH Variable Content:

  • Windows Platform (DOS Command Line): C:\> set CLASSPATH=

  • UNIX Platform (Bourne shell): # unset CLASSPATH; export CLASSPATH

Set CLASSPATH Variable:

  • Windows Platform (DOS Command Line): C:\> set CLASSPATH=C:\users\jack\java\classes

  • UNIX Platform (Bourne shell): # CLASSPATH=/home/jack/java/classes; export CLASSPATH