0

This is how my class definition goes:

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;

... and so on...

This is a method in the class definition, where a new object of this class is created inside the method:

 //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]))


 }

My question is, can I access the Object[] items of the newbag object from inside this method definition? Like this: newbag.items[i]

RockAndaHardPlace
  • 417
  • 1
  • 7
  • 18

1 Answers1

3

You can access it.

It is feasable to do:

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;
    }
}

because

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

See Access private field of another object in same class

Community
  • 1
  • 1
Cydrick Trudel
  • 9,957
  • 8
  • 41
  • 63