Local Classes

A local class is a class that is declared anywhere that a local variable is declared. A local class has the same scope as a local variable.

A local class has a name and can be reused. A local class instance can access the surrounding scope's local final variables and final parameters.


class MyClass {
  void myMethod(final int x) {
    final int y = x;
    
    class LocalClass {
      int a = x;
      int b = y;
    }
    
    LocalClass lc = new LocalClass();
    System.out.println(lc.a);
    System.out.println(lc.b);
  }
}

public class Main {
  public static void main(String[] args) {
    MyClass ec = new MyClass();
    ec.myMethod(10);
  }
}

The following code declares an Iterator interface and Iter inner class.

 
class Item{
  private String name;
  private String value;
  
  public Item(String n, String v){
    name = n;
    value = v;
  }
  public String toString(){
    return name + value;
  }
}

interface Iterator {
  boolean hasMoreElements();

  Object nextElement();
}

class ItemManager {
  private Item[] itemArray;
  private int index = 0;

  ItemManager(int size) {
    itemArray = new Item[size];
  }

  Iterator iterator() {
    class Iter implements Iterator {
      int index = 0;

      @Override
      public boolean hasMoreElements() {
        return index < itemArray.length;
      }

      @Override
      public Object nextElement() {
        return itemArray[index++];
      }
    }
    return new Iter();
  }

  void add(Item item) {
    itemArray[index++] = item;
  }
}

public class Main {
  public static void main(String[] args) {
    ItemManager itemManager = new ItemManager(5);
    itemManager.add(new Item("#1", "A"));
    itemManager.add(new Item("#2", "B"));
    itemManager.add(new Item("#3", "C"));
    Iterator iter = itemManager.iterator();
    while (iter.hasMoreElements()){
      System.out.println(iter.nextElement());
    }
      
  }
}
  
Home 
  Java Book 
    Class  

Nested Classes:
  1. Nested Types
  2. Nonstatic Member Classes
  3. Anonymous Classes
  4. Local Classes