What is inner class?

What is inner class?

  • An inner class or nested class is a class declared entirely within the body of another class.
  • The class that include the inner class is called outer class.
  • The inner class can access the methods & var. of outer class but not voice-versa.
  • Within the defination of inner class or outer class ,the modifier public & private are equivalents.
  • In Java there are 2 types of nested classes:
    A)static:
    i) It can defined using the modifier static.
    ii) It can’t access the member directly but only through an object.
    B) Non-Static:
    i) It can access the member of enclosed classes.
Syntax
class Outerclass
{
//code
class Innerclass
{
//code
}
}
Example
class A
{
private int x=10;
class B
{
public int y=20;
void fun()
{
System.out.println(“OUTER:”+x);
System.out.println(“INNER:”+y);
}
}
void display()
{
B obj=new B();
obj.fun();
}
}
class test
{
public static void main(String args[])
{
A obj1=new A();
obj1.display();
}
}

Output:
OUTER:10
INNER:20

 

Leave a Reply

Your email address will not be published. Required fields are marked *