基于类的私有访问权限(学习 Java 编程语言 028)

方法可以访问调用这个方法的对象的私有数据。一个方法可以访问所属类的所有对象的私有数据

class Employee{
    ...
    @Override
    public boolean equals(Object otherObject)
    {
        // a quick test to see if the objects are identical
        if (this == otherObject) return true;

        // must return false if the explicit parameter is null
        if (otherObject == null) return false;

        // if the classes don't match, they can't be equal
        if (getClass() != otherObject.getClass())
            return false;

        // now we know otherObject is a non-null Employee
        Employee other = (Employee) otherObject;

        // test whether the fields have identical values
        return Objects.equals(name, other.name)
                && salary == other.salary
                && Objects.equals(hireDay, other.hireDay);
    }
}

public class Manager extends Employee {
    ...
}

典型的调用方式是:

Employee harry = new Employee("Harry Hacker", 50000, 1989, 10, 1);
Manager boss = new Manager("Carl Cracker", 75000, 1987, 12, 15);

if(harry.equals(boss))...

这个 equals 方法访问 harry 的私有字段,这点并不会让人奇怪,不过,它还访问了 boss 的私有字段。这是合法的,其原因是 boss 是 Employee 类型对象,而 Employee 类的方法可以访问任何 Employee 类型对象的私有字段。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容