Core Java Tutorial: Packages & Access Control

Master package declaration, resolution paths, visibility scopes, and importing in Java.

1. Defining a Package

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.

Syntax & Example

// 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/.

2. Understanding CLASSPATH

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.

How Java Finds Classes:

Usage Example

# Compiling a class 
javac -d . com/myapp/utils/MathHelper.java

# Running a program by specifying the classpath target
java -cp . com.myapp.MainApp

3. Access Protection

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

4. Importing Packages

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.

Types of Imports

Complete Code Example

// 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);
    }
}