Sunday, 30 October 2016

NESTED AND INNER CLASSES

Tags

NESTED CLASS : CLASS CREATED WITHIN A CLASS

PROGRAM FOR NESTED CLASS

public class outer {
      int x =10;
     
      void fun(){
            inner i1 = new inner();
            i1.display();
      }
     
     
      class inner{
            int y =200;
           
            void display(){
                  System.out.println("x = "+x);
            }
      }
     
      void showy(){
            System.out.println("y ="+y);     // error //
      }

      public static void main(String[] args) {
           
            outer o1 = new outer();
            o1.fun();
           

      }

}
OUTPUT : X=10

BUT Y CAN'T BE ACCESSED AS OUTER CLASS CANNOT ACCESS INNER CLASS DE VARIABLES


ADVANTAGES OF NESTED CLASSES : 

1. HERE, INNER CLASS CAN ACCESS ALL MEMBERS OF OUTER CLASS INCLUDING OUTER                                                           CLASS VARIABLES AND METHODS.
2. IT MAKES CODE MORE READABLE
3. IT MAKES CODE MORE MAINTAINABLE
4. CODE OPTIMIZATION : MEANS IT NEED LESS CODE TO WRITE


DIFFERENCE BETWEEN INNER CLASS AND NESTED CLASS

* NESTED CLASS CAN BE STATIC AS WELL AS NON - STATIC.BUT INNER CLASS IS ALWAYS NON - STATIC

TYPES OF INNER CLASSES:  3 TYPES

1. MEMBER INNER CLASS : CLASS CREATED WITHIN CLASS AND OUTSIDE OUTER CLASS        METHOD.

2.ANNONYMOUS INNER CLASS : CLASS CREATED FOR IMPLEMENTING INTERFACE OR EXTENDING CLASSES


3. LOCAL INNER CLASS : INNER  CLASS CREATED WITHIN  OUTER  CLASS METHOD


Enter Your Comments Below Emoticon