Nested Inner Class

Inner class, also called nested class, is a class declared inside another class.

When a class is useful to just one other class, and no other role to play except as a helper class, it is best to declare it as an inner class.

public class Store {
	private Item[] items;
	private int count=0;
	private static final int  defaultCount=5;
	public Store() {
		this(defaultCount);
	}
	public Store(int number) {
		items = new Item[number];
	}
	public void addItem(String name, int quantity) {
		if(count < items.length) {
			Item item = new Item(name,quantity);
			items[count++] = item;
		}
	}
	public int getQuantity(String itemName) {
		for(Item item : items) {
			if(item.getName().equalsIgnoreCase(itemName)) {
				return item.getQuantity();
			}
		}
		return 0;
	}

	private class Item {
		private String name;
		private int quantity;

		Item(String name, int quantity) {
			this.name = name;
			this.quantity = quantity;
		}

		public String getName() {
			return name;
		}

		public int getQuantity() {
			return quantity;
		}
	}

	public static void main(String[] argsv) {
		Store box = new Store();
		box.addItem("pencil", 2);
		box.addItem("eraser", 1);
		box.addItem("pen", 3);
		box.addItem("book", 4);
		box.addItem("sharpner", 1);
		box.addItem("cover", 2);	// will be ignored

		int pens = box.getQuantity("pen");
		System.out.println("No. of pens in the box = "+pens);
	}
}

Note how the nested class holds the item data together. It promotes encapsulation. It is easy to maintain as well.

The nested class in the exanple above is declared private and therefore it is accessed like any other private data member of the enclosing class.

A nested inner class may be declared static too. As a static inner class, access to the members of its outer class is limited to static members only.

A method may also nest a class. A class declared inside a method is called a local class if it has a name, or an anonymous class if it is not given a name.