java - 比较类 equals 函数适用于私有(private)变量?

标签 java equals private comparable

好吧,我的代码可以工作,但我就是不明白为什么在这种情况下,函数 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 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 - 比较类 equals 函数适用于私有(private)变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21803247/

相关文章:

java - 无法在控制台模式下通过 java exec 命令运行 JMeter 5.0

java - 有没有办法检查两个集合是否包含相同的元素,与顺序无关?

java - 了解有关类的 FindBugs 警告不会覆盖父类(super class)中的等于

java - 另一个与 main 方法中的变量交互的类

c# - 如何在 WPF 中将控件标记为 'Private'?

java - java中的X和Y坐标循环

java - 使用来自 Apache Commons Collections 的 MultiValueMap

java - Maven 在构建时包括旧的 SNAPSHOT

html - 根据 child 的高度设置 parent 的高度

C++ 继承 : Can't access private element of base class