Tuesday 21 January 2014

INTRODUCING NESTED AND INNER CLASSES

NESTED CLASSES IN JAVA

A class declared inside a class is known as nested class. We use nested classes to logically group classes in one place so that it can be more readable and maintainable code. Moreover, it can access all the members of outer class including private members.


Advantage of nested classes

There are basically three advantages of nested classes. They are,

  • Nested classes represent a special type of relationship that is it can access all the members (data members and methods) of outer class including private.
  • Nested classes can lead to more readable and maintainable code because it logically group classes in one place only.
  • Code Optimization as we need less code to write.


Syntax of Nested class:

class Outer_class_Name
{  
 ...  
 class Nested_class_Name
{  
  ...  
 }  
 ...  
}  

Types of Nested class:

There are two types of nested classes non-static and static nested classes.

1.non-static nested class(inner class)
              a)Member inner class
              b)Annomynous inner class
              c)Local inner class
2.static nested class

1.non-static nested class(inner class):

A class that is declared inside a class but outside a method is known as member inner class.The non-static nested classes are also known as inner classes.

Invocation of Member Inner class
  1. From within the class
  2. From outside the class

Example of member inner class that is invoked inside a class:

In this example, we are invoking the method of member inner class from the display method of Outer class.

class Outer
{  
 private int data=30;  
 class Inner{  
  void msg(){System.out.println("data is "+data);
}  
 }  
   
 void display(){  
  Inner in=new Inner();  
  in.msg();  
 }  
 public static void main(String args[])
{  
  Outer obj=new Outer();  
  obj.display();  
 }  
}  
Output:data is 30

2.Static nested class:

A static class that is created inside a class is known as static nested class. It cannot access the non-static members.It can access static data members of outer class including private.static nested class cannot access non-static (instance) data member or method.

Program of static nested class that have instance method:

class Outer
{
  static int data=90;

  static class Inner
{
   void msg(){System.out.println("data is "+data);
}
  }
   public static void main(String args[])
{
  Outer.Inner obj=new Outer.Inner();
  obj.msg();
  }
}  

Output:
data is 90






4 comments :