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

I recently noticed unexpected behavior of accessing priavte fields in Java. Consider the following example to illustrate 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(ai); // 2. Accessing private field of another object! } public static void main(String[] args) { (new A(5)).foo(new A(2)); } } 

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

+6
source share
3 answers

Private fields protect the class, not the instance. The main goal is to allow the implementation of the class regardless of its API. Isolating instances between themselves or protecting instance code from static code of the same class will not do anything.

+13
source

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

You will need this access for many purposes. For example, when implemented, it is equal to:

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

The foo method belongs to the same class as the i variable, it does not harm to allow such access.

0
source

Source: https://habr.com/ru/post/945159/


All Articles