Nested class in JAVA

Nested class in JAVA

Nested Classes in Java. In java, it is possible to define a class within another class known as  Nested Classes.
Scope is bounded by its enclosing class.
   If class B is defined within class A, then B does not exist independently of A
   B can access all private members of A but A can not access private members of B
   Nested class is a member of its enclosing class. 
Nested classes are divided into two categories:
1.Static nested class :
                Nested classes that are declared static are called static nested classes.
2.Inner class(Non-static nested) : 
                An inner class is a non-static nested class.


Syntax:
class OuterClass
{
...
    class NestedClass
    {
        ...
    }
}



Inner class(Non-Static nested)

create object in non-static nested class:
outer o1=new outer();                    //first outer class object and then inner class object 
outer.inner i1=o1.new inner();

Example:

class outer{
     int a=50;
    class inner{                                      //Non-static nested class
        void Innerf1(){
        System.out.println("A="+a);
        }
    }
}
public class Nested {
    public static void main(String[] args) {
        outer o1=new outer();                 //outer class object(o1)
        outer.inner i1=o1.new inner();    // inner class object(i1)
        i1.Innerf1();                                // call the function of inner class
    }
}

Ourput:

A=50



Static nested class 

create object in static nested class:
        outer.inner i1=new outer.inner(); 

NOTE:-Not need to create a object of outer class in Static nested class.
              In Static nested class we call direct inner class function.

Example:

class outer{
     static int  a=50;
 static class inner{                                                       //static nested class
        void Innerf1(){
        System.out.println("A="+a);
        }
    }
}
public class Nested {
    public static void main(String[] args) {
       /* outer o1=new outer();
        Note: not need a created object of outer class
       */
         outer.inner i1=new outer.inner();                               // inner class object(i1)
        i1.Innerf1();// call the function of inner class
    }
}

Output:

A=50






More will come idea if you watch this video:-


Post a Comment

0 Comments