سؤال

Well my code works, but I just can't understand why a private variable works in this case, inside function equals().

Or is it just a trick that if you call another object from inside the same kind of object structure then the private identifier doesn't count?

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;
    }
}
هل كانت مفيدة؟

المحلول

Yes, these modifiers are class definition scoped not instance scoped. Check JavaOO tutorials and 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.

نصائح أخرى

"Or it's just a trick if you call another Object from inside the same kind of Object structure then private identifier doesn't count?" - simply, yes.

EDIT Official explanation:

"The first (left-most) modifier used lets you control what other classes have access to a member field. For the moment, consider only public and private. Other access modifiers will be discussed later. public modifier—the field is accessible from all classes. private modifier—the field is accessible only within its own class."

(http://docs.oracle.com/javase/tutorial/java/javaOO/variables.html)

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top