Local Classes

In this chapter you will learn:

  1. How to define a local class
  2. How to create a local class and return it from a method

Local class vs local variable

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 {//j av a 2s.co  m
  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);
  }
}

Return a local class

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

class Item{//from  ja  v  a2 s .c om
  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());
    }
      
  }
}

The output:

Next chapter...

What you will learn in the next chapter:

  1. What is class inheritance