Declaring and Organizing
Package Declaration Syntax
The basic syntax for declaring a package is straightforward:
package com.labex.projectname;
Creating Package Directories
In Ubuntu, create package directories to match the package declaration:
mkdir -p com/labex/projectname
Package Structure Example
graph TD
A[Project Root] --> B[com]
B --> C[labex]
C --> D[projectname]
D --> E[model]
D --> F[service]
D --> G[util]
Package Organization Strategies
Strategy |
Description |
Use Case |
Functional Grouping |
Organize by functionality |
Separate models, services, utilities |
Layer-based Grouping |
Organize by architectural layers |
Presentation, business logic, data access |
Feature-based Grouping |
Organize by application features |
User management, payment processing |
Multiple Class Declaration in a Package
package com.labex.tutorial;
public class UserManager {
// User management methods
}
public class AuthenticationService {
// Authentication-related methods
}
Importing Packages
Single Class Import
import com.labex.tutorial.UserManager;
Wildcard Import
import com.labex.tutorial.*;
Nested Packages
package com.labex.project.module.submodule;
public class NestedExample {
// Nested package implementation
}
Practical Packaging Workflow
- Plan your project structure
- Create corresponding directory hierarchy
- Declare packages at the top of each class
- Use appropriate import statements
- Compile with package-aware commands
Compilation and Execution Example
## Create directory structure
mkdir -p com/labex/tutorial
## Create Java files
nano com/labex/tutorial/HelloWorld.java
## Compile the package
javac com/labex/tutorial/HelloWorld.java
## Run the packaged class
java com.labex.tutorial.HelloWorld
Best Practices for Package Organization
- Keep packages focused and cohesive
- Use meaningful and descriptive package names
- Avoid overly deep package hierarchies
- Minimize circular dependencies
- Follow consistent naming conventions
Package Visibility Modifiers
Modifier |
Package Visibility |
public |
Accessible everywhere |
default |
Accessible within the same package |
protected |
Accessible within the same package and subclasses |
private |
Not accessible outside the class |