Reputation: 2739
Hi all someone can explain why the last line at this code is legal:
public class HashCodeTest {
private String value = null;
HashCodeTest(String value) {
this.value = value;
}
public static void main(String[] args) {
Map<HashCodeTest, String> aMap = new HashMap<HashCodeTest, String>();
aMap.put(new HashCodeTest("test"), "test");
aMap.put(new HashCodeTest("test"), "test");
System.out.println(aMap.size());
}
@Override
public int hashCode() {
int result = 17;
return 31 * result + value.hashCode();
}
public boolean equals(HashCodeTest test) {
if (this == test) {
return true;
}
if (!(test instanceof HashCodeTest)) {
return false;
}
return test.value.equals(value);
}
}
At the last line there is access to private field of test class but this is illegal.
Thanks, Maxim
Upvotes: 2
Views: 457
Reputation: 16252
Access modifiers define access for a type, not the instance of a type.
Upvotes: 0
Reputation: 726479
value
is not a private variable of another class; it is a private variable of another instance of the same class. Therefore the access is completely legal.
Upvotes: 4
Reputation: 117569
Because it is an instance of the same class you are using it in.
Upvotes: 4