Packages in Java
What is a Package?
A package in Java is a namespace that groups related classes and interfaces together. Think of it like a folder in your computer — it helps organize your files (classes) and avoid name conflicts.
Why Use Packages?
| Feature | Description |
|---|---|
| Namespace Control | Avoids name clashes between classes from different packages. |
| Code Organization | Helps organize large projects logically (like utils, models, controllers). |
| Access Protection | Supports access modifiers (e.g., protected, package-private). |
| Reusability | Classes can be reused across projects via imports. |
Types of Packages
| Type | Description | Example |
|---|---|---|
| Built-in | Provided by Java (JDK) | java.util, java.io |
| User-defined | Created by developers for custom use | package myapp.utils; |
Syntax of Defining a Package
At the top of the .java file:
package myproject; // define package name
public class Hello {
public void greet() {
System.out.println("Hello from ShikshaSanchar!");
}
}
How to Use a Class from a Package
You need to import it before using:
import myproject.Hello;
public class Main {
public static void main(String[] args) {
Hello h = new Hello();
h.greet();
}
}
Example: Creating and Using a Package
File: myapp/Student.java
package myapp;
public class Student {
public void show() {
System.out.println("Student class inside 'myapp' package");
}
}
File: Test.java (outside the package)
import myapp.Student;
public class Test {
public static void main(String[] args) {
Student s = new Student();
s.show();
}
}
Output:
Student class inside 'myapp' package
Folder Structure:
Project Root/
│
├── myapp/
│ └── Student.java
│
└── Test.java
Compile with:
javac myapp/Student.java
javac -cp . Test.java
java Test
Summary
| Feature | Explanation |
|---|---|
| Definition | Container for related classes/interfaces |
| Syntax | package packagename; at the top of file |
| Usage | import packagename.ClassName; |
| Types | Built-in (java.util), User-defined |
| Benefits | Organization, name conflict resolution, access control |