Nested Class Concept

  • 0
      Java language allows nesting of classes. When one class in defined in another class, then, enclosed class is called nested class. A nested class can access the methods and variables of the enclosing class, even private members, like they all are members of its own.

     On the contrary, enclosing class does not has access to any members of the enclosed class. It can be said that for the enclosing class, enclosed class does not exists. However, Nested class can not occur independently of the enclosing class. In other words, an instance of nested class can only be created in the scope of enclosing class. Java program for Nested Class Illustration is as.

package ClassIllustration;

class Outer
{
 int outer_x = 100;
 
 void test()
 {
  Inner inner = new Inner();
  inner.display();
 }
 class Inner
 {
  int inner_x = 50;
  void display()
  {
   System.out.println("Displaying outer_x " + outer_x);
   System.out.println("Displaying inner_x " + inner_x);
  }
 }
}

class InnerDemo
{
 public static void main(String args[])
 {
  Outer outer = new Outer();
  outer.test();
 }
}
To compile the program
javac -d . InnerDemo.java
And to run the program
java ClassIllustration.InnerDemo
The output that I obtained
Displaying outer_x 100
Displaying inner_x 50

No comments:

Post a Comment