Inner class
Nested Classes
Classes that are declared inside the body of a class
are called nested".
Why to use?
It is a way of logically grouping classes that are only
used in one place
It increases encapsulation: hiding classes can be
achieved.
It can lead to more readable and maintainable code.
Nested class is of 2 kinds:
Inner class
Static nested class
Nested class behaves just like any other member of its
enclosing (outer) class.
class Outer_Demo{
int num;
//inner class
private class
Inner_Demo{{
public void print(){
System.out.println("This
is an inner class");
}
}
void display_Inner(){
Inner_Demo inner =
new Inner_Demo();
inner.print();
}
public class My_class{
public static void main(String
args[]){
Outer_Demo outer=new
Outer_Dem();
outer.display_Inner();
}}
Output
This is an inner class.
public class My_class2{
public static void main(String
args[]){
class Outer_Demo {
//Instantiating the outer class
Outer_Demo outer=new
private int num= 175;
Outer_Demo();
public class Inner_Demo{
//Instantiating the inner class
public int getNum(){
Outer_Demo.Inner_Demo
inner=outer.new
System.out.println("This
Inner_Demo();
is the getnum method of
the inner class");
System.out.println(inner.getNu
return num;
m());
}
}
}
}
}
Output
The value of num in the class
Test is: 175
class Outer
{
static int data=30;
static class Inner
{
void msg() // instance method
{ System.out.println("data is "+data);
}
}
public static void main(String args[])
{
Outer.Inner obj=new Outer.Inner();
obj.msg();
}
}
Output:data is 30
class Outer{
static int data=30;
static class Inner
{
static void msg() //static method
{
System.out.println("data is "+data);
}
}
public static void main(String args[])
{
Outer.Inner.msg();
//no need to create the instance of sta
tic nested class
}
}