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.

3
  • What's your question? Why shouldn't they be accessible? Commented Mar 15, 2018 at 20:43
  • 1
    One of main reasons nested classes exist, is to let direct access of its members (including private ones) to outer class(es) and vice-versa. Commented Mar 15, 2018 at 20:45
  • 1
    There is no inner class here, only a nested static class. Commented Mar 15, 2018 at 23:10

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.