好吧,我的代码可以工作,但我就是不明白为什么在这种情况下,函数 equals()
内部的 private
变量可以工作。
或者这只是一个技巧,如果您从同类对象结构内部调用另一个对象,那么 private
标识符不算数?
public class TestClass implements Comparable <TestClass> {
private final String name;
public TestClass(String name) {
this.name = name;
}
@Override
public int hashCode() {
return name.hashCode();
}
@Override
public boolean equals(Object obj) {
if (obj instanceof TestClass) {
return ((TestClass) obj).name.equals(name); //<- how does this work, isn't name private?
} else {
return false;
}
}
@Override
public int compareTo(TestClass test) {
int thisValue = hashCode();
int otherValue = test.hashCode();
if (thisValue < otherValue) {
return -1;
} else if (thisValue > otherValue) {
return 1;
} else {
return 0;
}
}
@Override
public String toString() {
return name;
}
}
最佳答案
是的,这些修饰符是类定义范围的,而不是实例范围的。检查JavaOO tutorials和 Java Language Specification :
Otherwise, if the member or constructor is declared private, then access is permitted if and only if it occurs within the body of the top level class (§7.6) that encloses the declaration of the member or constructor.
关于java - 比较类 equals 函数适用于私有(private)变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21803247/