可以从该对象的 class 定义中的方法内部访问新对象的私有成员吗?

Can a private member of a new object be accessed from inside a method in the class definition of that object?

我的 class 定义是这样的:

public class ArrayBag implements Bag {
    /** 
     * The array used to store the items in the bag.
     */
    private Object[] items;

    /** 
     * The number of items in the bag.
     */
    private int numItems;

...等等...

这是class定义中的方法,在方法内部创建了这个class的新对象:

 //creates and returns an Arraybag that is the union of the called Arraybag and the parameter bag
 public bag unionWith(Bag other) {

     if (other == null)
           throw new IllegalArgumentException(); 

     int cap = this.capacity() + other.capacity();

     //new object created here      
     ArrayBag newbag = new ArrayBag(cap);

     for (int i = 0; i < numItems; i++) {

           if (other.contains(items[i])) 

                 newbag.add(items[i]);

     }

     for (int i = 0; i < newbag.numItems(); i++)

        //Can I use "newbag.items[i]"?
        if (numOccur(newbag.items[i]))


 }

我的问题是,我可以从这个方法定义中访问 newbag 对象的 Object[] 项吗?像这样:newbag.items[i]

您可以访问它。

可行:

public class AClass {
    private int privateInteger;
    public AClass() {
        privateInteger = 5;
    }
    // First way 
    public void accessFromLocalInstance() {
        AClass localInstanceOfClass = new AClass()
        int valueOfLocalInstance = localInstanceOfClass.privateInteger;
    }
    // Second way
    public void accessFromInstance(AClass instance) {
        int valueOfInstance = instance.privateInteger;
    }
}

因为

"private" means restricted to this class, not restricted to this object.

Access private field of another object in same class