Java - Local Inner Class

Introduction

A local inner class is declared inside a block.

Its scope is limited to the block in which it is declared.

Its declaration cannot use any access modifiers such as public, private, or protected.

A local inner class is defined inside a method, inside static initializers, non-static initializers, and constructors.

The following code shows an example of a local inner class.

Demo

import java.util.ArrayList;
import java.util.Iterator;

class TitleList {
  private ArrayList<String> titleList = new ArrayList<>();

  public void addTitle(String title) {
    titleList.add(title);/*w ww .ja  v a  2s . com*/
  }

  public void removeTitle(String title) {
    titleList.remove(title);
  }

  public Iterator<String> titleIterator() {
    class TitleIterator implements Iterator<String> {
      int count = 0;

      @Override
      public boolean hasNext() {
        return (count < titleList.size());
      }

      @Override
      public String next() {
        return titleList.get(count++);
      }
    }
    TitleIterator titleIterator = new TitleIterator();
    return titleIterator;
  }
}

public class Main {
  public static void main(String[] args) {
    TitleList tl = new TitleList();
    tl.addTitle("A");
    tl.addTitle("tutorial from book2s.com");
    Iterator<String> iterator = tl.titleIterator();
    while (iterator.hasNext()) {
      System.out.println(iterator.next());
    }
  }
}

Result