1

Consider the following example:

import java.util.ArrayList;

public class Invoice {

    private static class Item {
        String description;
        int quantity;
        double unitPrice;

        double price() { return quantity * unitPrice; }
    }

    private ArrayList<Item> items = new ArrayList<>();

    public void addItem(String description, int quantity, 
                        double unitPrice) {
        Item newItem = new Item();
        newItem.description = description;
        newItem.quantity = quantity;
        newItem.unitPrice = unitPrice;
        items.add(newItem);
    }

}

I understand that the nested class is only visible to the enclosing outer class. However I have following question.

Why are we allowed to directly access an instance variable of the inner class newItem.description? Is this because the default visibility modifier is public in this class for the instance field? Usually we would have a series of setter and getter methods.

Furthermore, I tried making one of the instance variables of the nested class private (private int quantity) yet the compiler still did not complain.

Mutating Algorithm
  • 2,604
  • 2
  • 29
  • 66

0 Answers0