Saturday, November 16, 2013

Java Inner Class Example

Create a class OuterClass with the following:
  • a private integer variable outerX with value 10
  • printOuterX()
  • sayHello() with a local inner class named LocalInnerClass and an anonymous inner class.

The LocalInnerClass is as shown below:
 
class LocalInnerClass {
    public void greetInLocal() {
    System.out.println("Hello World in LocalInnerClass!!");
    }

    public void printXInLocal() {
    System.out.println("outerX :" + outerX + " in LocalInnerClass");
    }
}

//The anonymous inner class AnonymousInnerClass as shown below:

class AnonymousInnerClass {
   public void printHelloWorld() {
   System.out.println("Hello World in AnonymousInnerClass!!");
   }
}

The main() should make a call to OuterClass's sayHello() method.
Modify the sayHello() such that the following output is obtained:
Hello World in LocalInnerClass!!
outerX :10 in LocalInnerClass
Hello World in sayHello!!
outerX :10 in AnonymousInnerClass

Solution:

public class InnerClassExample {

 public static void main(String[] args) {
  OuterClass obj= new OuterClass();
  obj.displayX();
  obj.sayHello();
 }

}

class OuterClass
{
 private int OuterX=10;
 void displayX(){
  System.out.println("X="+OuterX+"  In OuterClass");
 }
 
 void sayHello(){
  class LocalInnerClass {
   public void greetInLocal() {
    System.out.println("Hello World in LocalInnerClass!!");
   }
   public void printXInLocal() {
    System.out.println("outerX :" + OuterX + " in LocalInnerClass");
   } 
  }
   
  LocalInnerClass local2 = new LocalInnerClass();
  LocalInnerClass local1 = new LocalInnerClass(){
   public void greetInLocal(){
    System.out.println("outerX :" + OuterX + " in AnnonymousClass");
   }
  };
  
  local2.greetInLocal();
  local2.printXInLocal();  
  System.out.println("Hello World in sayHello!!");
  local1.greetInLocal();
 }
}

No comments:

Post a Comment