Master package declaration, resolution paths, visibility scopes, and importing in Java.
A Package acts as a container for group-related classes, interfaces, and sub-packages. It prevents naming conflicts and controls access permissions.
To declare a package, use the package keyword as the very first non-comment statement in your source file.
// File: src/com/myapp/utils/MathHelper.java
package com.myapp.utils;
public class MathHelper {
public static int add(int a, int b) {
return a + b;
}
}
Directory Structure: Java maps package names directly to filesystem folders using dots as separators. The file above must reside in the folder path com/myapp/utils/.
CLASSPATH is an environment variable (or command-line flag) that tells the Java Virtual Machine (JVM) and Java compiler (javac) where to look for user-defined packages and classes.
.): By default, the current working directory is searched.CLASSPATH.-cp or -classpath flag during compilation and execution.# Compiling a class
javac -d . com/myapp/utils/MathHelper.java
# Running a program by specifying the classpath target
java -cp . com.myapp.MainApp
Packages serve as visibility boundaries. Java provides four levels of access control to determine whether other classes can access a field, method, or constructor.
| Access Modifier | Same Class | Same Package | Subclass (Different Package) | World (Different Package) |
|---|---|---|---|---|
private |
Yes | No | No | No |
| Default (No modifier) | Yes | Yes | No | No |
protected |
Yes | Yes | Yes | No |
public |
Yes | Yes | Yes | Yes |
To use a class located in a different package, you must either refer to it by its Fully Qualified Name or use the import statement.
import com.myapp.utils.MathHelper;
import com.myapp.utils.*;
import static java.lang.Math.PI;
import static java.lang.Math.sqrt;
// File: src/com/myapp/MainApp.java
package com.myapp;
// Importing explicit class from another package
import com.myapp.utils.MathHelper;
public class MainApp {
public static void main(String[] args) {
int result = MathHelper.add(10, 20);
System.out.println("Result: " + result);
}
}