Why can a clone set a private field on another object?

I am learning Java, and the book I am reading has the following example of cloning. In clone() my first instance can set a buffer for a new object, even if the buffer is private . It seems like this requires the field to be protected for this.

Why is this allowed? Does clone() special privileges that allow it to access private fields?

 public class IntegerStack implements Cloneable { private int[] buffer; private int top; // ... code omitted ... @Override public IntegerStack clone() { try{ IntegerStack nObj = (IntegerStack) super.clone(); nObj.buffer = buffer.clone(); return nObj; } catch (CloneNotSupportedException e) { throw new InternalError(e.toString()); } } } 
+3
source share
1 answer

The private modifier does not mean that only the same instance can access the field; this means that only objects of the same class can access it.

The Java language specification says in ยง6.6, Access control :

... if a member or constructor is declared private, then access is allowed if and only if it occurs inside the body of a top-level class (ยง7.6) , which contains the declaration of the member or constructor.

In other words, anything inside the class can access it at any time. Even nested classes can access private members and constructors in the enclosing class and vice versa.

(You are not alone in a misunderstanding, look at this multitasking answer to the question: "What was your longest programmed assumption wrong? )

+16
source

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


All Articles