Introduction
In this article, we discuss nested classes (inner classes) in Java.
Nested class
One of the nice and highly advantageous features of Java is the ability to define nested classes, in other words, classes within classes. In Java classes are either top-level-classes (a class defined directly within a package) or nested classes (classes defined within top-level-classes).
Syntax:
class MainClass
{
//some coding here
class NestedClass
{
//some coding here
}
}
Advantages
The main advantages of a nested (inner) class are:
- It shows a special type of relationship, in other words, it has the ability to access all the data members (data members and methods) of the main class including private.
- They provide easier code because it logically groups classes in only one place.
- Reduces coding since we need less code to write.
Types
This can be divided into two categories:
- static class
- non-static class is also called as inner classes.
Static Classes
For creating an object, the syntax is:
Example
- class Main
- {
- static int value=430;
- static class Inner
- {
- void mesg()
- {
- System.out.println("Data value is " + value);
- }
- }
- public static void main(String[] args)
- {
- Main.Inner c=new Main.Inner();
- c.mesg();
- }
- }
Output

Non-static class (Inner class)
This class refers directly to its instance variables or methods defined in its enclosing class. Also, because an inner class is associated with an instance, it cannot define any static members itself.
The syntax for a non-static class is:



Join the conversation! Your thoughts help the community grow.