1. What are Packages?
Definition
Packages in Java are a mechanism for organizing related classes, interfaces, and
sub-packages into a single namespace. They provide a way to group related
code elements and prevent naming conflicts.
Syntax
java
package com.example.mypackage;
public class MyClass {
// class implementation
}
Key Characteristics
Hierarchical Structure: Packages follow a directory-like structure
Naming Convention: Reverse domain name convention
(e.g., com.company.project)
Access Control: Packages influence access modifiers (default/package-private
access)
2. Advantages of Using Packages
1. Organization and Structure
java
// Without packages - messy
class User {}
class Product {}
class Order {}
// With packages - organized
// com.example.model.User
// com.example.model.Product
// com.example.service.OrderService
2. Name Conflict Prevention
java
// Two different Date classes can coexist
java.util.Date utilDate = new java.util.Date();
java.sql.Date sqlDate = new java.sql.Date();
3. Access Control
Package-private: Classes/members accessible only within the same package
Protected: Accessible within package and to subclasses
4. Code Reusability
java
// Reuse across projects
import com.example.utilities.StringUtils;
import com.example.database.ConnectionPool;
5. Modular Development
java
// Separate teams can work on different packages
// com.example.ui.* (UI team)
// com.example.database.* (Database team)
// com.example.business.* (Business logic team)
6. Security
Internal implementation details can be hidden using package-private access
3. Accessing Packages from Another Package
Import Statements
java
// Specific class import
import java.util.ArrayList;
// Wildcard import
import java.util.*;
// Static import
import static java.lang.Math.PI;
Fully Qualified Names
java
// Without import
java.util.ArrayList<String> list = new java.util.ArrayList<>();
// With import
import java.util.ArrayList;
ArrayList<String> list = new ArrayList<>();
Access Modifiers and Package Visibility
java
package com.example.package1;
public class ClassA {
public int publicVar; // Accessible everywhere
protected int protectedVar; // Accessible in package + subclasses
int packageVar; // Accessible only in package
private int privateVar; // Accessible only in class
}
java
package com.example.package2;
import com.example.package1.ClassA;
public class ClassB {
public void method() {
ClassA obj = new ClassA();
obj.publicVar = 10; // OK - public
// obj.protectedVar = 20; // Error - different package, not subclass
// obj.packageVar = 30; // Error - different package
// obj.privateVar = 40; // Error - private
}
}
4. Subpackaging
Definition
Subpackages are packages within packages, creating a hierarchical structure.
Structure
text
src/
└── com/
└── example/
├── model/ # Subpackage
│ ├── User.java
│ └── Product.java
├── service/ # Subpackage
│ ├── UserService.java
│ └── ProductService.java
└── util/ # Subpackage
└── StringUtils.java
Important Notes about Subpackages
java
// Subpackages DO NOT inherit access privileges
package com.example.model;
public class User {
protected String name; // Not accessible in com.example.service
}
package com.example.service;
import com.example.model.User;
public class UserService {
public void processUser(User user) {
// user.name = "John"; // Error - different package
}
}
5. Running Packages with PATH and CLASSPATH
Directory Structure for Compilation
text
project/
├── src/
│ └── com/
│ └── example/
│ ├── Main.java
│ └── util/
│ └── Calculator.java
└── bin/
Compilation Process
1. Compile with package structure:
bash
# From project directory
javac -d bin src/com/example/Main.java src/com/example/util/Calculator.java
2. Compile all files in directory:
bash
javac -d bin src/com/example/*.java src/com/example/util/*.java
Setting CLASSPATH
Method 1: Using -cp flag
bash
# Run from project directory
java -cp bin com.example.Main
# Or set CLASSPATH environment variable
export CLASSPATH=bin:$CLASSPATH
java com.example.Main
Method 2: Using manifest file (for JAR)
bash
# Create manifest file
echo "Main-Class: com.example.Main" > manifest.txt
# Create JAR
jar cfm myapp.jar manifest.txt -C bin .
# Run JAR
java -jar myapp.jar
Advanced CLASSPATH Examples
Multiple paths in CLASSPATH:
bash
# Unix/Linux/Mac
export CLASSPATH=bin:lib/*:../shared-lib/*:$CLASSPATH
# Windows
set CLASSPATH=bin;lib/*;../shared-lib/*;%CLASSPATH%
Running with external libraries:
bash
java -cp "bin:lib/mysql-connector.jar:lib/commons-lang.jar" com.example.Main
Common Issues and Solutions
1. ClassNotFoundException:
bash
# Wrong: Running from wrong directory
java Main # Error
# Right: Specify classpath
java -cp bin com.example.Main
2. NoClassDefFoundError:
bash
# Missing dependencies in classpath
java -cp "bin:missing-library.jar" com.example.Main # Error
# Include all required JARs
java -cp "bin:lib/*" com.example.Main
3. Package directory structure mismatch:
bash
# Ensure compiled classes are in correct directory structure
# bin/com/example/Main.class
# bin/com/example/util/Calculator.class
Best Practices
1. Package Naming
java
// Use reverse domain name
package com.companyname.projectname.module;
// Avoid overly deep nesting
// Good: com.example.dao
// Avoid: com.example.project.dao.database.connection.pool.impl
2. Import Organization
java
// Group imports logically
import java.util.*; // Java standard library
import java.sql.*; // Java SQL packages
import javax.servlet.*; // External libraries
import javax.servlet.http.*;
import com.example.model.*; // Project-specific packages
import com.example.util.*;
3. Access Control
java
package com.example.dao;
// Use package-private for internal implementation
class DatabaseConnection { // Not public - internal to package
// implementation
}
public class UserDAO { // Public API
private DatabaseConnection connection;
// public methods
}
4. Build Tools
bash
# Use Maven/Gradle for complex projects
# Maven automatically handles classpath and compilation
mvn compile
mvn exec:java -Dexec.mainClass="com.example.Main"
Real-World Example
Project Structure
text
ecommerce-app/
├── src/
│ └── com/
│ └── example/
│ ├── ecommerce/
│ │ ├── model/
│ │ │ ├── Product.java
│ │ │ ├── User.java
│ │ │ └── Order.java
│ │ ├── service/
│ │ │ ├── ProductService.java
│ │ │ └── OrderService.java
│ │ └── Main.java
│ └── util/
│ └── Validator.java
└── lib/
├── log4j.jar
└── gson.jar
Compilation and Execution
bash
# Compile
javac -d bin -cp "lib/*" src/com/example/ecommerce/model/*.java \
src/com/example/ecommerce/service/*.java \
src/com/example/ecommerce/Main.java \
src/com/example/util/*.java
# Run
java -cp "bin:lib/*" com.example.ecommerce.Main