Inner/ Nested Class in Java
Introduction of java Inner Class:
- Java inner class or nested class is a class that is declared inside the class or interface.
- Next Unit Discuss details in class and interface with opp all topics.
- When a class is used inside the body of the another class then is used inside the body of another class then this concept is called inner class concept.
- Just like nested-if and nested-loop one class inside another class is called nested class.
- Inner class represent a particular type of relationship that is access all members of data-members and members functions of the outer class.
- Inner class provide write less code.
- It is also called nesting of class.
Syntax:-
- For better understanding of inner class see the below example
// Example 1: Find add program using inner class.
class OuterAdd{ //Create OuterClass
public void outadd(){ // create outer methods
int a=10, b=20, c;
c=a+b;
System.out.println("Addition of Outer Class Value: "+c);
}
class InnerAdd{ //create InnerClass
public void inadd(){ // create inner methods
int x=5, y=8, z;
z=x+y;
System.out.println("Addition of Inner Class Value: "+z);
}
}
}
class Inner{ // Create main function
public static void main(String args[]){
OuterAdd obj=new OuterAdd();
obj.outadd();
OuterAdd.InnerAdd obj1= obj.new InnerAdd();
obj1.inadd();
}
}
Explanation:-
- In this example explanation just focus on creating the instance(object) of InnerAdd class you got something new.
- The Object of InnerAdd is creating with the reference of OuterAdd because InnerAdd exists inside of OuterAdd.
I hope this post is helpful for you. So Don't forget follow me.
THE END
Comments