John Threepwood
John Threepwood

Reputation: 16143

Why is it allowed to access a private field of another object?

Recently, I observed an unexpected behavior of accessing priavte fields in Java. Consider the following example, which illustrates the behavior:

public class A {

    private int i;  <-- private field!

    public A(int i) {
        this.i = i;
    }

    public void foo(A a) {
        System.out.println(this.i);  // 1. Accessing the own private field: good
        System.out.println(a.i);     // 2. Accessing private field of another object!
    }

    public static void main(String[] args) {
        (new A(5)).foo(new A(2));
    }
}

Why I am allowed to access the private field of another object of class A within the foo method (2nd case)?

Upvotes: 8

Views: 299

Answers (3)

Ric
Ric

Reputation: 1114

The foo method belongs to the same class as does the variable i there is no harm in allowing such an access.

Upvotes: 0

Mohayemin
Mohayemin

Reputation: 3870

This is because they are of the same class. This is allowed in Java.

You will need this access for many purposes. For example, in an implementation of equals:

public class A {
  private int i;

  @override public boolean equals(Object obj){
     if(obj instanceof A){
        A a = (A) obj;
        return a.i == this.i; // Accessing the private field
     }else{
       return false
     }
  }
}

Upvotes: 4

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382102

Private fields protect a class, not an instance. The main purpose is to allow a class to be implemented independently of its API. Isolating instances between themselves, or protecting the instance's code from the static code of the same class would bring nothing.

Upvotes: 14

Related Questions