Inner class in Java.
Inner class in Java
1.When a class is used inside the body of another class then this concept is called inner class concept.
2.Just like nested-if and nested-loop one class inside another class is called nested class.
3.Inner class is also called Nesting of class.
Syntax
class OuterAddition
{
class InnerAddition
{
}
}
Example
For better understanding of inner class see the below example.
class OuterAddition
{
//creating outer class method
public void outAdd()
{
int x,y=10,z=20;
x=y+z;
System.out.println("outAdd="+x);
}
//creating inner class
class InnerAddition
{
//creating inner class method
public void inAdd()
{
int x,y=50,z=20;
x=y+z;
System.out.println("inAdd="+x);
}
}
}
class Easy
{
public static void main(String[] args)
{
//Creating instance(object) of OuterAddition class
OuterAddition obj=new OuterAddition();
//calling OuterAddition function
obj.outAdd();
//Creating instance(object) of InnerAddition class
OuterAddition.InnerAddition obj2=obj.new InnerAddition();
//calling InnerAddition function
obj2.inAdd();
}
}
/*
### Output ###
outAdd=30
inAdd=70
*/
Just focus on creating the instance(object) of InnerAddition class you got something new.The object of InnerAddition is creating with the reference of OuterAddition because InnerAddition exists inside OuterAddition.