In this article we will look at what is a nested class and how to define a nested class and access the nested class members in a Java program.
Java 1.1 added support for nested classes. A class defined as a member of another class definition is known as a nested class. A nested class can be either static or non-static. The non-static nested class is known as an inner class.
The enclosing class of an inner class can be called as an outer class. An inner class can access all the members of an outer class. But the outer class cannot access the inner class members. Inner classes and anonymous classes (inner classes without a name) are useful in event handling.
Below Java program demonstrates inner class (non-static nested class):
public void showDetails()
System.out.println("Age: " + age);
System.out.println("Name: " + name);
public void show()
Details d = new Details();
public static void main(String args)
Person p = new Person();
p.age = 25;
p.name = "surya";
In the above example Details is the inner class and Person is the outer class.