ProgrammingBackend Developer

What is package-private access level in Java, how does it work and when should it be used?

Pass interviews with Hintsage AI assistant

Answer

In Java, package-private is the "default" access level (without specifying visibility modifiers: public, protected, private). Such a class member (method, field, or the class itself) is accessible only from classes within the same package.

  • Declaration:
    class MyClass { /* ... */ } void doSomething() { /* ... */ }
  • Not accessible outside the package, not inherited as protected.
  • Used for internal package logic, to protect the implementation from external access while allowing access to internal package code.

Example:

// File: com/example/internal/Helper.java class Helper { static void help() { System.out.println("helped"); } }

Always use package-private if the class or method is an internal implementation detail.

Trick Question

Question: Can a package-private class be visible within another package through inheritance or import?

Answer: No, package-private members cannot be accessed through inheritance or import from other packages — they are only accessible within their own package.

Examples of real errors due to lack of understanding of the topic


Story

In a large project, different teams started using package-private classes for utility logic. When they tried to reuse the code from other packages, it didn't work — access was impossible. As a result, they had to make the classes public, which exposed the internal implementation.


Story

In a multi-module project, package-private classes caused issues when writing unit tests: tests in another package couldn't see package-private methods, and they had to move the tests inside the original package or relax the access level.


Story

When migrating code to a new package, there were unexpected compile-time errors — many methods and classes unexpectedly "disappeared" because they were package-private and became inaccessible after the package change.