Inner Classes – Examples


Example 1: Inner classes

class A {
   class B { } // a class inside of a class
  
   void f(int i) {

      class C { } // a class inside of a method
      
      if(i > 0) {
         class D { // a class inside of an if statement
            C c = new C();
         } 
      }
   }
   
   // D d; // D unkown - out of the scope!

   void m() {  
      B b = new B(); // an object of an inner class
      // C c; // C unkown - out of the scope!
   }
}

public class M {
   public static void main(String[] args) {
      (new A()).f(-1);
   }
}


_____________________________________________________________________


Example 2: Providing an instance of an inner/anonymous class using an external interface

interface I {
   void m();
}

class A {
   I f1() { // the f1() method can't return a value of the B type - that's why an external interface is necessary
      class B implements I {
         public void m() {
            System.out.println("From an inner B class...");
         }
      }
      return new B();
   }

   I f2() { // like f1(), but using an anonymous class
      return new I() {
         public void m() {
            System.out.println("From an anonymous class...");
         }
      };
   }
}

public class M {
   public static void main(String[] args) {
      I b1 = (new A()).f1();
      b1.m();

      I b2 = (new A()).f2();
      b2.m();
   }
}


_____________________________________________________________________


Example 3: Using inner/anonymous classes to transfer a functionality into a differnet context

interface I {
   void m();
}

class C {
   void h(I i) {
      i.m();
   }
}

public class M {
   public static void main(String[] args) {
      C c1 = new C();
      
      class H implements I {
         public void m() {
            System.out.println("Processing an event with an inner class...");
         }
      }
      
      c1.h(new H());
      
      
      C c2 = new C();
      
      c2.h(new I() {
         public void m() {
            System.out.println("Processing an event with an anonymous class...");
         }        
      });
   }
}


Valentino Vranić
vranic at stuba.sk