A protected field in Java is a member field declared with theDocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
protected access modifier, restricting its visibility to the declaring class, classes within the same package, and subclasses located in any package. It provides a strictly wider access level than package-private (default) visibility by explicitly permitting cross-package access strictly through inheritance.
Syntax
Theprotected keyword precedes the data type in the field declaration:
Visibility Matrix
Java enforces the following access boundaries for a protected field:- Same Class: Accessible
- Same Package (Subclass): Accessible
- Same Package (Non-subclass): Accessible
- Different Package (Subclass): Accessible (with strict inheritance context constraints)
- Different Package (Non-subclass): Not Accessible
Cross-Package Inheritance Mechanics
The most complex mechanical rule regarding protected fields involves cross-package access. When a subclass resides in a different package than the superclass defining the protected field, the subclass can only access the protected field through an inheritance context. The rules differ depending on whether the field is an instance field or astatic field.
- Instance Fields: The subclass can access the field on instances of itself or its own subclasses. It cannot access the protected field on an object reference of the superclass type.
- Static Fields: The subclass can access a protected static field via its own type name (or implicitly without qualification). It cannot access the protected static field via the superclass type name.
Code Demonstration
Access Enforcement and Memory Model
Theprotected modifier is enforced at both compile-time and run-time. At compile-time, javac validates the access boundaries. At run-time, the JVM enforces these boundaries during resolution and linkage, throwing an IllegalAccessError if a violation occurs (e.g., if class files were recompiled separately and access levels changed). Additionally, the Reflection API enforces these rules dynamically, throwing an IllegalAccessException if unauthorized access is attempted.
Applying the protected modifier does not alter how the field is allocated in memory. During object instantiation, memory is allocated for a protected instance field on the Heap exactly as it would be for private, public, or default fields. Protected static fields are stored on the Heap as part of the java.lang.Class instance during class loading, identical to other static fields.
Master Java with Deep Grasping Methodology!Learn More





