gpt4 book ai didi

java - Comparable Class equals 函数适用于私有(private)变量?

转载 作者:行者123 更新时间:2023-11-30 08:26:03 25 4
gpt4 key购买 nike

好吧,我的代码可以工作,但我只是不明白为什么 private 变量在这种情况下工作,在函数 equals() 内。

或者这只是一个技巧,如果您从同一类型的对象结构中调用另一个对象,那么 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 tutorialsJava 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 - Comparable Class equals 函数适用于私有(private)变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21803247/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com