方法可以访问调用这个方法的对象的私有数据。一个方法可以访问所属类的所有对象的私有数据。
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 类型对象的私有字段。