Packages are containers for classes/interfaces. It is a namespace that organizes a set of related classes and interfaces. It is like a folder in the file system that groups related files together.
Package is defined using keyword package
followed by the package name at the very beginning of the Java source file. The package name typically follows a hierarchical naming convention that is usually based on the reverse domain name of the organization.
package com.example.myapp;
public class ExampleClass {
public int publicVar = 1;
protected int protectedVar = 2;
int packagePrivateVar = 3; // No modifier, package-private by default
private int privateVar = 4;
public void printVars() {
System.out.println("publicVar: " + publicVar);
System.out.println("protectedVar: " + protectedVar);
System.out.println("packagePrivateVar: " + packagePrivateVar);
System.out.println("privateVar: " + privateVar);
}
}
Naming Conventions
- Lowercase Letters: Package names should be written in lowercase letters to avoid conflict with class names.
- Hierarchical Structure: Use dots to separate different levels of the hierarchy.
File System Correspondence
- The directory structure of your project should mirror the package hierarchy.
- For example, a class defined in the package
com.example.myapp
should be placed in the directorycom/example/myapp
.
Sub-Packages
Packages can contain sub-packages, and these are declared in the same way as regular packages. The naming hierarchy ensures that classes are organized in a logical structure.
Package can be categorized in two forms
- Built-In Package
- User-Defined Package
Built-In Packages
These are packages that come with the Java Development Kit (JDK) and provide a large collection of ready-to-use classes and interfaces. eg java.lang
, java.util
, java.io
, java.net
import java.util.ArrayList;
public class BuiltInPackageExample {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Cherry");
for (String fruit : list) {
System.out.println(fruit);
}
}
}
User-Defined Package
User-defined packages are created by programmers/developers to organize their own classes and interfaces.