一个子类的对象可以访问另一个子类的另一个对象的受保护字段吗?

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

我从核心 Java 一书的第一卷——基础(第 8 版)> 第 5 章:继承 > 'Protected Access' 部分(第 205 页)中学到了以下内容。

There are times, however, when you want to restrict a method to subclasses only or, less commonly, to allow subclass methods to access a superclass field. In that case, you declare a class feature as protected. For example, if the superclass Employee declares the hireDay field as protected instead of private, then the Manager methods can access it directly.

However, the Manager class methods can peek inside the hireDay field of Manager objects only, not of other Employee objects. This restriction is made so that you can’t abuse the protected mechanism and form subclasses just to gain access to the protected fields.

我写了下面的代码来测试一下

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);
    }
}

代码的输出是:

$ java TestProtectedAccess
name: Alice Employee
name: Charles Executive

Manager 对象 m 能够访问其他 Employee 对象 eex 的受保护字段 name。这似乎与我上面从书中引用的内容相矛盾,尤其是我用粗体突出显示的部分。

如果书有误或者我的理解有误,有人可以解释一下吗?如果我的理解有误,你能推荐一个更好的例子来理解这本书的意思吗?

由于您的 类 都在同一个包中,因此 protected 与 public 相同。

The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package.

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