Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 420
Maxim Kirilov Avatar asked May 07 '26 17:05

Maxim Kirilov


2 Answers

Private fields are accessible by all instances of this class.

like image 156
MByD Avatar answered May 10 '26 18:05

MByD


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

like image 25
Eng.Fouad Avatar answered May 10 '26 19:05

Eng.Fouad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!