Packages
Perfect β letβs explore Packages in Java next. This topic is essential for modular design, code organization, and access control in large applications.
π§ What Are Packages in Java?
A package in Java is like a folder in your system that groups related classes and interfaces together. It helps organize code, avoid class name conflicts, and control access levels.
Think of it like arranging your Java files in folders, so things donβt get messy as your project grows.
π Why Use Packages?
Benefit | Explanation |
---|---|
β Modularity | Related classes stay together logically and physically. |
β Avoid Naming Conflicts | Two classes with the same name can live in different packages. |
β Access Control | You can use protected and default (package-private) visibility. |
β Reusable Code | Easily reuse utility or domain packages across projects. |
π§ Types of Packages
- Built-in Packages: Provided by the Java SDK.
- Examples:
java.util
,java.io
,java.lang
, etc.
- Examples:
- User-defined Packages: You create your own to organize your codebase.
π§± Example: Creating and Using a Package
Step 1: Create a User-Defined Package
π File: mypackage/MessagePrinter.java
package mypackage;
public class MessagePrinter {
public void print() {
System.out.println("Hello from the package!");
}
}
πΈ
package mypackage;
must be the first line in the file.
Step 2: Use the Package in Another File
π File: Main.java
import mypackage.MessagePrinter;
public class Main {
public static void main(String[] args) {
MessagePrinter printer = new MessagePrinter();
printer.print();
}
}
β Compile & Run:
From the directory above mypackage
, run:
javac mypackage/MessagePrinter.java
javac Main.java
java Main
π Package and Access Modifiers
- Default (no modifier): Class is accessible only within its own package.
protected
: Accessible in the same package and in subclasses even if they’re in different packages.public
: Accessible from everywhere.private
: Still only within the same class, unaffected by packages.
This makes packages essential for implementing Javaβs access control and encapsulation mechanisms.
βοΈ Best Practices
- Use meaningful package names, often based on reverse domain structure (e.g.,
com.myapp.services
). - Group related classes (e.g., controllers, models, services, utils).
- Avoid mixing unrelated classes in one package.
- Use access modifiers effectively to protect internals of your package.
π Homework for Students
Create a package named
university
containing the following classes:Student
withname
,rollNumber
and a methoddisplayDetails()
.Teacher
withname
,subject
and a methoddisplayDetails()
.
In a separate file (outside the package), import both classes and:
- Create objects for each.
- Call their
displayDetails()
method.
Try to:
- Access a class with default visibility from another package.
- Use
protected
andpublic
modifiers and observe access behavior.
Would you like to cover Access Modifiers next, or dive into Static Keyword or Interface vs Abstract Class?