nested classes tutorial java code example

Example 1: Nested classes in java

// example on inner class in java
class OuterDemo
{
   int num;
   // inner class
   private class InnerDemo
   {
      public void display()
      {
         System.out.println("inner class");
      }
   }
   // access inner class from method within
   void printInner()
   {
      InnerDemo objInner = new InnerDemo();
      objInner.display();
   }
}
public class InnerClassExample
{
   public static void main(String[] args)
   {
      OuterDemo objOuter = new OuterDemo();
      objOuter.printInner();
   }
}

Example 2: Nested classes in java

// how to access private members of a class.
class OuterClass
{
   // outer class private variable
   private int number = 56;
   // inner class
   public class InnerClass
   {
      public int showNumber()
      {
         System.out.println("showNumber() method of inner class.");
         return number;
      }
   }
}
public class AccessPrivateMembers
{
   public static void main(String[] args)
   {
      OuterClass objOuter = new OuterClass();
      OuterClass.InnerClass objInner = objOuter.new InnerClass();
      System.out.println(objInner.showNumber());
   }
}

Tags:

Java Example