Package relevance:
All classes belong to a package.
The default (global) package is used if none is specified, but is not suitable for large projects.
Creating a package:
Use the package statement at the beginning of a source file.
The package statement defines a namespace for the classes in the file.
Example package definition:
package mypack;
Package management in the file system:
Each package is stored in its own directory on the file system.
The directory must have the same name as the package, taking case into account.
Package hierarchy:
Packages can be organized hierarchically with multiple levels.
Example of package hierarchy:
package alpha.beta.gamma;
In the file system, this hierarchy will be reflected as .../alpha/beta/gamma.
Shared use of packages:
Multiple files can include the same package statement, allowing multiple classes to be part of the same package.
Code Example
Directory Structure:
src/ mypack/ MyClass.java Main.java
package mypack; public class MyClass { public void displayMessage() { System.out.println("Olá do pacote mypack!"); } }
import mypack.MyClass; // Importando a classe MyClass do pacote mypack public class Main { public static void main(String[] args) { MyClass myClass = new MyClass(); // Criando uma instância de MyClass myClass.displayMessage(); // Chamando o método da classe } }
Explanation:
The mypack package was defined in the MyClass.java file with the package.
statement
The MyClass class belongs to the mypack package, being accessed and used in the main Main class through import mypack.MyClass.
Program output:
Hello from mypack!
The above is the detailed content of Defining a Package. For more information, please follow other related articles on the PHP Chinese website!