java Nested Class 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

// example on static nested classes java
import java.util.*;
public class OuterClass
{
   static class NestedClass
   {
      public void display() 
      {
         System.out.println("static nested class example");
      }
   }
   public static void main(String[] args) 
   {
      OuterClass.NestedClass nested = new OuterClass.NestedClass();	 
      nested.display();
   }
}

Example 3: Nested classes in java

// anonymous inner class as method argument.
interface HelloWorld
{
   String print();
}
public class AnonymousInnerDemo
{
   // method accepts object of interface HelloWorld
   public void display(HelloWorld m)
   {
      System.out.println(m.print() + "example of anonymous inner class as method argument.");
   }
   public static void main(String[] args)
   {
      AnonymousInnerDemo obj = new AnonymousInnerDemo();
      // pass an anonymous inner class as an argument
      obj.display(new HelloWorld() {
         public String print() {
            return "Hi! ";
         }
      });
   }
}

Example 4: Nested classes in java

// example on method local inner class in java.
class Outer
{
   // outer class instance method
   void display()
   {
      int num = 96;
      // method-local inner class
      class MethodLocalInner
      {
         public void show()
         {
            System.out.println("in method local inner class " + num);
         }
      } // end of inner class
      // access method local inner class
      MethodLocalInner objInner = new MethodLocalInner();
      objInner.show();
   }
   public static void main(String[] args)
   {
      Outer objOuter = new Outer();
      objOuter.display();
   }
}

Example 5: inner class vs outer class

1. Can Outer class be static? --> No
2. Can inner class be static? --> Yes
3. Can you create an object from the inner class? --> Only if it's static
4. Can we have main method in inner class ? --> Only if it's static
5. Inner class can only be extended if it's static.

Example 6: use of nested class in java

In Java, it is possible to define a class within another class, such 
classes are known as nested classes. They enable you to logically group 
classes that are only used in one place, thus this increases the use of 
encapsulation, and creates more readable and maintainable code.

Tags:

Java Example