Inner Classes

An inner class is a class whose body is defined inside another class, referred to as the top-level class. For example:

public class Queue {

  Element back = null;

  public void add(Object o) {
  
    Element e = new Element();
    e.data = o;
    e.next = back;
    back = e;
    
  }
     
  public Object remove() {
  
    if (back == null) return null;
    Element e = back;
    while (e.next != null) e = e.next;   
    Object o = e.data;
    Element f = back;
    while (f.next != e) f = f.next;   
    f.next = null;
    return o;
    
  }
     
  public boolean isEmpty() {
    return back == null;
  }

  // Here's the inner class
  class Element {
  
    Object data = null;
    Element next = null;
    
  }

 }

Inner classes may also contain methods. They may not contain static members.

Inner classes in a class scope can be public, private, protected, final, abstract.

Inner classes can also be used inside methods, loops, and other blocks of code surrounded by braces ({}). Such a class is not a member, and therefore cannot be declared public, private, protected, or static.

The inner class has access to all the methods and fields of the top-level class, even the private ones.

The inner class's short name may not be used outside its scope. If you absolutely must use it, you can use the fully qualified name instead. (For example, Queue$Element) However, if you need to do this you should almost certainly have made it a top-level class instead or at least an inner class within a broader scope.

Inner classes are most useful for the adapter classes required by 1.1 AWT and JavaBeans event handling protocols. They allow you to implement callbacks. In most other languages this would bo done with function pointers.


Previous | Next | Top | Cafe au Lait

Copyright 1997 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified July 24, 1997