Definition of Packages: A package in Java is a namespace that organizes classes and
interfaces. It helps manage the code by grouping related classes together, avoiding naming
conflicts, and enabling better modularity and reusability.
Key Features of Packages:
1. Organization: Helps group similar classes and interfaces.
2. Access Control: Enables controlled access using access modifiers (e.g., public,
protected).
3. Namespace Management: Avoids naming conflicts by providing unique
namespaces.
4. Reusability: Encourages reusability of code across projects.
Creating a Package: To create a package:
1. Declare the package at the top of the Java file using the package keyword.
2. Compile the file to place it in a directory structure matching the package name.
Example:
// File: MyPackage/MyClass.java
package MyPackage;
public class MyClass {
public void displayMessage() {
System.out.println("Hello from MyPackage!");
}
}
After compiling, the directory structure will look like MyPackage/MyClass.class.
Importing User-Defined Packages: To use a package in another program:
1. Import the package using the import keyword.
2. Use fully qualified names if not importing explicitly.
Example:
import MyPackage.MyClass;
public class Main {
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.displayMessage();
}
}
Java Application Programming Interface (API):
Java provides a rich set of built-in libraries (Java API) organized into packages like
java.util, java.io, etc.
Developers can also create custom APIs by defining reusable packages, promoting
modularity and efficient application development.