ProgrammingJava Developer

Describe how the protected access modifier works in Java, what distinguishes it from other modifiers, and what mistakes can occur from its misunderstanding.

Pass interviews with Hintsage AI assistant

Answer.

The protected access modifier allows class members to be visible within the same package and in all subclasses, even if they are in different packages.

Differences from other modifiers:

  • private — access only within the current class
  • default (no modifier) — accessible only within the current package
  • protected — accessible within the current package and in subclasses outside the package
  • public — accessible everywhere

Example:

package com.example.base; public class Parent { protected void sayHello() { System.out.println("Hello from parent"); } } package com.example.child; import com.example.base.Parent; public class Child extends Parent { public void tryHello() { sayHello(); // Access is granted! } } public class NotChild { public void fail(Parent p) { // p.sayHello(); // Error: no access } }

Tricky Question.

Can a non-subclass external class access a protected method from another package, having an object of that class?

Answer: No, access to a protected method from another package is allowed only for subclassing classes, and only through this or through a reference to an instance of the subclass, not to the parent.

Parent p = new Child(); p.sayHello(); // Error! ((Child) p).sayHello(); // Success (if called within Child)

Examples of real errors due to ignorance of the topic's nuances.


Story

In a large modular project, a developer placed important business methods in the protected section, thinking they were inaccessible outside the package. Other developers accidentally used these methods in tests within the same package, and due to subsequent class relocations, unexpected access errors occurred.


Story

In a microservices project, a method with protected access was attempted to be called by a reference to a parent type in another package — the call did not work. This caused a failure in parts of the system's extension mechanisms because it relied on an incorrect understanding of scope.


Story

In an open-source library, protected fields were carelessly used, which became accessible to too wide a range of classes, inadvertently damaging the internal state of the object, causing problems in third-party applications.