Can an object of a subclass access a protected field of another object of another subclass?

I learned the following from a Core Java book, Volume I - Fundamentals (8th Edition)> Chapter 5: Inheritance> "Secure Access" (p. 205).

However, there are times when you want to restrict the method to subclasses, or, less commonly, to allow subclasses to access the superclass field. In this case, you declare the class function as protected. For example, if an employee of the Superclass declares leaseDay as protected, and not private, then Manager methods can access it directly.

However, the methods of the Manager class can look inside the leaseDay field of only Manager objects, and not other Employee objects. . the restriction is made in such a way that you cannot abuse the protected mechanism and subclass only for access to protected fields.

I wrote the following code to test it.

class Employee { protected String name; public Employee(String name) { this.name = name; } } class Manager extends Employee { public Manager(String name) { super(name); } public void peekName(Employee e) { System.out.println("name: " + e.name); } } class Executive extends Employee { public Executive(String name) { super(name); } } public class TestProtectedAccess { public static void main(String[] args) { Employee e = new Employee("Alice Employee"); Manager m = new Manager("Bob Manager"); Executive ex = new Executive("Charles Executive"); // Manager object accessing protected name of Employee object m.peekName(e); // Manager object accessing protected name of Executive object m.peekName(ex); } } 

Code output:

 $ java TestProtectedAccess name: Alice Employee name: Charles Executive 

The Manager m object has access to the protected name field of other Employee e and ex objects. This seems to contradict what I quoted above from the book, especially the part that I highlighted in bold.

Can someone explain to me if the book is wrong or my understanding is wrong? If my understanding is wrong, can you offer a better example to understand what a book means?

+5
source share
1 answer

Since your classes are all in one package, protected is the same as public.

The protected modifier indicates that a member can only be accessed within its own package (as well as for a private package) and, in addition, a subclass of its class in another package.

https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

+2
source

Source: https://habr.com/ru/post/1233958/


All Articles