Programming Tutorials

How to use and access the inner class in java

By: Saravanan in Java Tutorials on 2009-10-03  

In this Tutorial we are going to see how to use a named inner class, how to access inner class in Java.

//A named inner class is used.
// This is used to show that it can access non-local variables in the enclosing object.

public class InnerExample
  {
  static String msg= "Welcome";

  public static void main(String[] arg)
    {
    class InnerClass {
      public void doWork()
      {
        System.out.println(msg);
      }
    }
    InnerClass i = new InnerClass();
    i.doWork();
  }
}

// Access inner class from outside 

public class InnerExample2
 {
    public static void main(String[] args)
    {
        OuterClass outer = new OuterClass();
        outer.new InnerClass().welcome();
    }
}

class OuterClass
 {
    public class InnerClass
    {
        public void welcome()
        {
          System.out.println("Welcome from InnerClass()");
        }
    }
}





Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in Java )

Latest Articles (in Java)