Java Packages
Java Packages
A package in Java is a namespace that organizes a set of related classes and interfaces. Using packages helps in avoiding name conflicts, improving code maintainability, and reusing code.
1. Types of Packages
Built-in Packages – Provided by Java API.
Example:
java.util,java.io,java.lang
User-defined Packages – Created by programmers to organize classes.
2. Creating a User-defined Package
Step 1: Create a Package
Step 2: Use the Package
📌 Output:
3. Accessing Classes in a Package
import packageName.className;→ Import a specific class.import packageName.*;→ Import all classes in the package.
Example:
4. Built-in Package Example
5. Advantages of Packages
Modularity – Organize classes into logical groups.
Name Conflict Avoidance – Classes with same name can exist in different packages.
Reusability – Packages can be reused in multiple programs.
Access Protection – Package-private access level helps encapsulation.
6. Key Points
| Feature | Description |
|---|---|
package keyword | Declares a package at the top of a file |
import keyword | Imports classes or entire package |
| Built-in packages | Provided by Java (e.g., java.util, java.io) |
| User-defined packages | Created by programmer to organize classes |
| Benefits | Modularity, Reusability, Name conflict avoidance, Access protection |
