When examining a class hierarchy, Eclipse mistakenly flags the access of a protected field as invalid. This apparent contradiction arises from a misunderstanding of the intended functionality of the protected modifier.
According to the Java Language Specification (JLS), a protected member is accessible within the declaring class's package and by subclasses of that class, regardless of the subclass's package. In this case, class A declares the protected field protectedInt.
In the given example, class C extends class A, which means that C instances should have access to A's protectedInt field. However, Eclipse reports that the access is prohibited when using an instance of A in C.
The solution lies in understanding that protected access is restricted to subclasses of the declaring class. Therefore, A's protectedInt field can only be accessed by instances of C or subclasses of C. This is a crucial distinction that Eclipse misses.
To illustrate, accessing protectedInt through an instance of C would work as intended:
C c = new C(); System.out.println(c.protectedInt); // Access to 'protectedInt' allowed
Ultimately, the protected modifier provides controlled access to fields and methods, allowing them to be inherited by subclasses while maintaining encapsulation within a package.
The above is the detailed content of Why Does Eclipse Flag Protected Field Access as Invalid in Java Inheritance?. For more information, please follow other related articles on the PHP Chinese website!