11.2 Inner classes 

Previous Index Next 


In version 1.1 of the Java an new kind of class was introduced. This type of class is called an inner class. An inner class is a class that is defined within another class.

An inner class can access attributes and methods of the class that it is a part of. For example:

public class TestClass
 {
  private int testInt=0;
 
  protected void showValue()
   {
    System.out.println("The int is " + testInt);
   }
 
  public void go()
   {
    TestInnerClass testInner = new TestInnerClass();
    testInner.increment();
   }
 
  public static void main(String[] args)
   {
    TestClass test = new TestClass();
    test.go();
   }
 }
In the example above the TestInner class can access the testInt attribute and call the showValue() method of the TestClass class.

Inner classes are used extensively when written GUI application. They are used to implement listeners and adapters which are covered in the next section.
 



Sources