Unit 8 (Prog 2) : Test Inner Class 2nd

By | June 13, 2013

In this example you will find Anonymous Inner class concepts, Inner class concepts in java, and also some tricks about Interface.

/*
 * TestAnonymousInnerClass.java
 *
 * This Example includes…
 *          1. Method inside Interface with body.
 *          2. Inner Class inside Interface.
 *          3. Anonymous Inner class of abstract class.
 *          4. Anonymous Inner class of non-abstract class.
 *          5. Anonymous Inner class of Interface.
 * */

abstract class OuterClass {
          abstract void outerMethod();
}

class AnotherOuterClass {
          public void anotherMethod() {
                    System.out.println("Outer Class Method.");
          }
}

interface OuterInterface {
          public void interfaceMethod();

          // inner class within an interface.
          class Inner {
                    public void methodInInterface() {
                              System.out.println("Hey...this is a method with body inside interface. :p");
                    }
          }
}

public class TestAnonymousInnerClass implements OuterInterface{

          @Override
          public void interfaceMethod() {
                    System.out.println("Unused !!!");
          }

           public static void main(String a[]) {
                     // Example of Abstract class.

                     OuterClass out = new OuterClass() {

                    // Anonymous Inner class of abstract class.

                              void outerMethod() {
                                    System.out.println("abstract method overriden by Anonymous inner class.");
                              }
                     };
                    out.outerMethod();

                    // Example of non-abstract class.
                   AnotherOuterClass anotherOut = new AnotherOuterClass() {
                             // Anonymous Inner class of non-abstract class.
                             public void anotherMethod() {
                             System.out.println("non-abstract Method overriden by anonymous inner class");
                             }
                   };

                  anotherOut.anotherMethod();

                  // example of interface.
                  OuterInterface inter = new OuterInterface() {
                  // Anonymous Inner class of interface.
                            public void interfaceMethod() {
                                 System.out.println("Thid is interface method from inner class.");
                            }
                  };
                  OuterInterface.Inner in = new Inner();
                  in.methodInInterface();
                  inter.interfaceMethod();
          }
}
email

Leave a Reply

Your email address will not be published. Required fields are marked *