Package Basics
What is a Package in Java?
In Java, a package is a way of organizing related classes, interfaces, and sub-packages. It provides a mechanism to group code into logical units, helping developers manage and structure their projects more effectively.
Package Naming Conventions
Packages in Java follow a specific naming convention:
- Use lowercase letters
- Reverse domain name notation is recommended
- Separate package names with periods
package com.labex.tutorial;
Package Structure and Directory Layout
The package structure should match the directory structure in your project:
graph TD
A[Project Root] --> B[src]
B --> C[com]
C --> D[labex]
D --> E[tutorial]
E --> F[MyClass.java]
Types of Packages
Package Type |
Description |
Example |
Built-in Packages |
Provided by Java |
java.util, java.lang |
User-defined Packages |
Created by developers |
com.labex.myproject |
Package Declaration
To declare a package, use the package
keyword at the beginning of your Java file:
package com.labex.tutorial;
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello from LabEx tutorial!");
}
}
Importing Packages
You can import specific classes or entire packages:
// Import specific class
import java.util.ArrayList;
// Import entire package
import java.util.*;
Benefits of Using Packages
- Code Organization
- Namespace Management
- Access Control
- Improved Maintainability
Compiling and Running Packaged Classes
On Ubuntu 22.04, compile and run packaged classes using:
## Compile
javac -d . MyClass.java
## Run
java com.labex.tutorial.MyClass
Understanding packages is crucial for writing well-structured and maintainable Java applications.