I'm learning Java, and the book I'm reading has the following example on cloning. In clone()
, my first instance is able to set buffer on the new object even though buffer is private
. It seems like it should require the field to be protected
for this to work.
Why is this allowed? Does clone()
have special privileges that allows it to access the 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());
}
}
}