1

Consider this piece of code:

class Capsule {
    private int numItems;

    private void moveItemsTo(Capsule that) {
        that.numItems += this.numItems;
        numItems = 0;
    }

    public static void main(String[ ] args) {
        Capsule c = new Capsule();
        c.numItems = 2000;
        c.moveItemsTo( c );
    }
}

When I first looked at it, I thought that the moveItemsTo() method would cause compilation errors, since it is accessing a private field from another instance of Capsule. Also, I thought that even in main, accessing the private fields of a newly created instance is not allowed. However, the entire code compiled without any errors, can someone please explain why?

b_pcakes
  • 2,452
  • 3
  • 28
  • 45

0 Answers0