Java Packages
πWhat is a Package in Java?
A package in Java is a namespace that groups related classes, interfaces, and sub-packages. It helps in code organization, reusability, and preventing name conflicts. Java packages also enhance security and access protection by restricting access to specific classes.
πTypes of Java Packages:-
Java provides two main types of packages:
- Built-in Packages β Provided by Java (e.g.,
java.util
,java.io
,java.sql
). - User-defined Packages β Created by developers to organize custom Java classes.
πHow to Create a Package in Java?
Follow these simple steps to create a package in Java:
πStep 1: Define a Package:
Use the package
keyword at the beginning of your Java file.
javapackage mypackage; // Declaring package
public class MyClass {
public void showMessage() {
System.out.println("Hello from MyClass inside mypackage");
}
}
πStep 2: Save and Compile the File:
Save the file as MyClass.java
and compile using:
shjavac -d . MyClass.java
The -d .
option creates a directory with the package name (mypackage
).
πHow to Use a Package in Java?
1. Importing a Package
To access a class from another package, import it using import
keyword:
javaimport mypackage.MyClass;
public class TestPackage {
public static void main(String args[]) {
MyClass obj = new MyClass();
obj.showMessage();
}
}
2. Importing All Classes from a Package:
Use *
to import all classes from a package:
javaCopyEditimport mypackage.*;
3. Using Fully Qualified Name:
Without import
, you can directly use the fully qualified name:
javamypackage.MyClass obj = new mypackage.MyClass();
πCreating Sub-Packages in Java:
A sub-package is a package inside another package.
πSteps to Create a Sub-Package:
Modify the package name with .
(dot notation):
javapackage mypackage.subpackage;
public class SubClass {
public void display() {
System.out.println("Inside SubClass of subpackage");
}
}
Compile:
shCopyEditjavac -d . SubClass.java
Execute:
shjava mypackage.subpackage.SubClass
πAdvantages of Using Java Packages Properly:-
- Better Code Organization: Helps in structuring large projects efficiently.
- Enhanced Code Reusability: Easily reuse classes across different projects.
- Improved Readability: Keeps code maintainable and modular.
- Naming Conflict Prevention: Avoids clashes between class names in large applications.
By structuring Java programs into well-defined packages, developers can create scalable and manageable codebases. Keep following best practices for efficient and error-free Java development! π