Java Local Classes
Description
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.
Example
Java Local Class
class MyClass {//from w w w . j a va 2s . c om
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 code above generates the following result.
Example 2
The following code declares an Iterator interface and Iter inner class.
class Item{// w w w .j a v a 2s . c o m
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: