In this tutorial, you will learn about the nested class in Java and its types with the help of examples.
In Java, it is possible to define a class within another class, such classes are known as nested classes. They enable you to logically group classes that are only used in one place, thus this increases the use of encapsulation, and creates more readable and maintainable code.
class OuterClass
{
...
class NestedClass
{
...
}
}
As with class methods and variables, a static nested class is associated with its outer class. And like static class methods, a static nested class cannot refer directly to instance variables or methods defined in its enclosing class: it can use them only through an object reference.
Example :
class Outer
{
static int data=30;
static class StaticNestedClass
{
void msg()
{
System.out.println("Data is "+data);
}
}
public static void main(String args[])
{
Outer.StaticNestedClass obj=new Outer.StaticNestedClass();
obj.msg();
}
}
Output :
Data is 30
Creating an inner class is quite simple. You just need to write a class within a class. Unlike a class, an inner class can be private and once you declare an inner class private, it cannot be accessed from an object outside the class.
class Outer
{
int num;
// inner class
private class Inner_Demo
{
public void print()
{
System.out.println("This is an inner class");
}
}
// Accessing he inner class from the method within
void display_Inner()
{
Inner_Demo inner = new Inner_Demo();
inner.print();
}
}
public class My_class
{
public static void main(String args[])
{
// Instantiating the outer class
Outer_Demo outer = new Outer_Demo();
// Accessing the display_Inner() method.
outer.display_Inner();
}
}
Output :
This is an inner class