Course contentsShow
← Java
Lesson 696 of 2,87017. Access Control in DepthFree lesson

Package-Private Classes (Default Access)

Explore classes with no explicit modifier and their visibility within the same package only.

Package-Private Classes (Default Access)

What you'll learn: How to create classes that are only visible within their own package by omitting the public keyword.

The Default Access Level

When you declare a class without any access modifier (no public, protected, or private keyword), it gets package-private or default access. This means the class is only accessible to other classes within the same package—it's invisible to classes in different packages.

Think of it like a neighborhood block party: everyone on your street (package) is invited, but people from other streets (packages) can't attend.

Why Use Package-Private Classes?

Package-private access is perfect for implementation details you want to hide from the outside world. If a class is only needed by other classes in the same package to support their functionality, there's no reason to make it public. This follows the principle of information hiding—exposing only what's necessary.

Syntax

// In file Helper.java (same package as Main.java)
class Helper {  // No 'public' keyword = package-private
    void assist() {
        System.out.println("Helping within the package!");
    }
}
// In file Main.java (same package as Helper.java)
public class Main {
    public static void main(String[] args) {
        Helper h = new Helper();  // Works fine—same package
        h.assist();
    }
}

If you tried to access Helper from a class in a different package, you'd get a compilation error—it's not visible there.

When to Choose Package-Private

Use package-private classes for internal utilities, data structures, or helper classes that support your public API but aren't meant for external use. This keeps your package's implementation flexible—you can change or remove these classes without affecting external code.

Key Takeaway: Classes without an access modifier have package-private (default) access, visible only within their own package—ideal for hiding implementation details.