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.