Object Oriented Programming in JavaUnit 77 min read
Packages, Access Modifiers & Java Modularity
Unit 7 of Object Oriented Programming in Java covers how to organize Java code into reusable packages, the four access modifiers (public, protected, default, private), their scope rules, and how to use them with classes, methods, and fields. Learn package declaration syntax, import statements, and how access control en
Core Concepts
1. Packages: Java’s Modular Organization
Packages group related classes/interfaces into namespaces to avoid naming conflicts and improve code reuse. They act like folders in a filesystem.
How Packages Work
- Declaration: Every
.javafile must start with a package statement (e.g.,package com.esewa.payment;). - Directory Structure: The package name maps to the filesystem path (e.g.,
com/esewa/payment/). - Importing: Use
importto access classes from other packages (e.g.,import java.util.*).
Example: eSewa’s Payment System
// File: com/esewa/payment/Transaction.java
package com.esewa.payment;
public class Transaction {
public void processPayment(double amount) {
System.out.println("Processing NPR " + amount + " via eSewa");
}
}
// File: Main.java (in default package)
import com.esewa.payment.Transaction;
public class Main {
public static void main(String[] args) {
Transaction txn = new Transaction();
txn.processPayment(500.00); // Output: Processing NPR 500.0 via eSewa
}
}
Figure: Package Hierarchy for eSewa
```mermaid
classDiagram
class com {
+esewa
}
class com.esewa {
+payment
}
class com.esewa.payment {
Transaction
}
com.esewa.payment --> Transaction : contains
2. Access Modifiers: Controlling Visibility
Access modifiers restrict how classes, methods, and fields can be accessed. They enforce encapsulation (hiding implementation details).
| Modifier | Class | Package | Subclass | World |
|---|---|---|---|---|
public |
✅ | ✅ | ✅ | ✅ |
protected |
✅ | ✅ | ✅ | ❌ |
default* |
✅ | ✅ | ❌ | ❌ |
private |
✅ | ❌ | ❌ | ❌ |
*No keyword needed (package-private).
Real-World Use in Ncell’s Billing System
package com.ncell.billing;
public class BillGenerator {
private double baseRate; // Only accessible within BillGenerator
protected String customerId; // Accessible to subclasses (e.g., PremiumBillGenerator)
public double calculateBill() { // Public API for clients
return baseRate * 30; // 30-day billing cycle
}
}
Figure: Access Modifier Scope
```mermaid
stateDiagram-v2
[*] --> World: public
[*] --> Package: protected
[*] --> Subclass: protected
[*] --> Class: private
3. Subtopics Breakdown
a) Package Naming Conventions
- Use reverse domain names (e.g.,
com.esewa,org.pokharauniversity). - Avoid top-level packages like
java,javax, orsun.
b) Import Statements
- Static Import: Import static members directly (e.g.,
import static java.lang.Math.PI;). - Wildcard Import:
import java.util.*(use sparingly to avoid naming conflicts).
c) Access Modifier Rules
- Class-Level Modifiers:
- Only
publicordefault(noprivate/protectedfor classes).
- Only
- Method/Field Modifiers:
private: Hide implementation (e.g.,private double calculateTax()).protected: Allow subclass access (e.g.,protected void validateCustomer()).
- Constructor Access:
- Controls object creation (e.g.,
private BankAccount()for singleton pattern).
- Controls object creation (e.g.,
d) Inheritance and Access Modifiers
- A subclass can access
protectedandpublicmembers of its parent. - Example: Daraz’s
Orderclass (protected fields forOrderProcessorsubclass).
package com.daraz.order;
public class Order {
protected String orderId; // Accessible to OrderProcessor
private double total; // Hidden from subclasses
}
Worked Example: Kathmandu Traffic Route Planner
Scenario: Simulate a traffic system where TrafficLight and Vehicle classes interact.
// File: com/kathmandu/traffic/TrafficLight.java
package com.kathmandu.traffic;
public class TrafficLight {
private String location; // e.g., "Thapathali"
protected boolean isRed;
public void changeLight() {
isRed = !isRed; // Toggle state
}
public boolean getStatus() {
return isRed;
}
}
// File: com/kathmandu/vehicle/Vehicle.java
package com.kathmandu.vehicle;
import com.kathmandu.traffic.TrafficLight;
public class Vehicle {
private String licensePlate;
protected TrafficLight currentLight;
public void move() {
if (currentLight.getStatus()) { // Access protected method
System.out.println("Stopping at " + currentLight.location);
} else {
System.out.println("Moving forward!");
}
}
}
Figure: State After changeLight() Call
```mermaid
stateDiagram-v2
TrafficLight: isRed = true
Vehicle: currentLight --> TrafficLight
Vehicle: move() --> "Stopping at Thapathali"
Common Pitfalls and Best Practices
Circular Dependencies:
- Avoid
PackageAimportingPackageBwhich importsPackageA. - Fix: Restructure into a common super-package.
- Avoid
Overusing
public:- Minimize public members to reduce coupling (e.g., expose only
getTotal()instead oftotal).
- Minimize public members to reduce coupling (e.g., expose only
Default Package:
- Avoid it for production code (leads to tight coupling).
Access Modifiers in Interfaces:
- All methods are
publicby default; fields arepublic static final.
- All methods are
In the Real World
eSewa’s Transaction Module
- Package:
com.esewa.payment - Access Control:
privatefields foramountandtransactionId;publicmethods likeprocessPayment(). - Why? Prevents external classes from directly modifying sensitive data.
- Package:
Ncell’s Billing System
- Package:
com.ncell.billing - Protected Methods:
validateCustomer()for subclasses likePremiumBillGenerator. - Why? Allows custom billing logic while enforcing validation rules.
- Package:
Daraz’s Order Processing
- Package:
com.daraz.order - Default Access:
OrderStatusenum accessible only within the package. - Why? Hides internal status codes from external APIs.
- Package:
Exam Tip
Package Questions:
- Always show the directory structure and
packagedeclaration in code. - Example: For a
com.university.gradepackage, draw:com/ └── university/ └── grade/ └── GradeCalculator.java
- Always show the directory structure and
Access Modifier Tricks:
- Common Exam Question: "Why can’t
MainaccessprivatefieldxinClassA?" Answer: Private members are only accessible within the same class. Use getters/setters for controlled access.
- Common Exam Question: "Why can’t
Code Tracing:
- For questions like "What happens when
BextendsAandAhas aprotectedmethod?", trace:- Can
BcallA'sprotectedmethod? Yes. - Can a class in another package call it? No (unless it’s
public).
- Can
- For questions like "What happens when
GUI + Packages:
- If asked to create a GUI form (e.g., even/odd checker), structure it as:
package com.tu.exam.gui; import javax.swing.*; - Use
defaultaccess for helper classes (e.g.,EvenOddCheckerHelper).
- If asked to create a GUI form (e.g., even/odd checker), structure it as:
Visual Summary
```mermaid
mindmap
root((Packages & Access Modifiers))
Concepts
Packages: Namespaces
Access Modifiers: public/protected/default/private
Real-World
eSewa: com.esewa.payment
Ncell: com.ncell.billing
Daraz: com.daraz.order
Exam Tips
Show directory structure
Trace access rules
GUI + package structure
Based on the TU BCA syllabus for Object Oriented Programming in Java (CACS204), unit 7.
Discussion
Loading…