• iconJava Online Training In Andhra Pradesh and Telangana
  • icon9010519704

Opening Hours :7AM to 9PM

Inner Class:


If one class with in another class is known as inner class or nested class
Syntax:
class classname — outer class
{
     class classname. — inner class
     {
     ...
     ...
     }
...
...
...
}

The main aim of the inner class is to provide more security for the data
Example class A
{
int x;
     class B
     {
     int y;
     float z;
     void f1()
     {
     ...
     ...
     }
     ...
     ...
     }
}

Key Points

Image
Accessing inner class properties:
1.outer class property can be access with in the inner class directly.
2.inner class properties can be accesses inside the outer class methods with object reference
3.properties of non-static innerclass can be accessed by creating a special object in the external class(Main class) as shown below

Outerclass.innerclass objref=new outerclass().new innerclass();

4.whenever we want to access static inner class property within external class then we must create a spacial object as shown below

Outerclass.innerclass objref=new outerclass.innerclass()

Write a java program to illustrate innerclass
class A
{
    int x=10;
    void f1()
    {
        System.out.println("this if f1 method");
    }
    void f2()
    {
        B ob=new B();
        ob.f4();
    }
    class B
    {
        int y=30;
        void f3()
        {
            System.out.println("x="+x);
            f1();
        }
        void f4()
        {
            System.out.println("this is  f4 method");
        }
    
    };
    static class C
    {
        void f5()
        {
            System.out.println("this is f5 method");
        }
    }
};
public class Rain {

    public static void main(String[] args)  {
        
        A oa=new A();
        oa.f2();
        A.B ob=new A().new B();// non static inner class object
        ob.f3();
        A.C oc=new A.C(); // static inner class object
        oc.f5();
        
    }
}


Output:
this is f4 method
x=10
this if f1 method
this is f5 method
Note:
Outer class or external class cont be declare either static or final class.