Maxim Kirilov
Maxim Kirilov

Reputation: 2739

Accessing private field in Java class from another class

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

Answers (4)

Derek Greer
Derek Greer

Reputation: 16252

Access modifiers define access for a type, not the instance of a type.

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

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

Eng.Fouad
Eng.Fouad

Reputation: 117569

Because it is an instance of the same class you are using it in.

Upvotes: 4

MByD
MByD

Reputation: 137272

Private fields are accessible by all instances of this class.

Upvotes: 4

Related Questions