In Java, Inner Classes are a component of Nested Classes, where a class is defined within another class. The specific characteristic of Inner Classes is that they are non-static. As a non-static nested class, an inner class has access to other members of the outer class, even if they are declared private. It's as if the inner class is a member of the outer class.
The structure looks like this:
class OuterClass
{
private int outerVariable = 1;
class InnerClass
{
public void displayOuterVariable()
{
System.out.println("Value of outerVariable in OuterClass is " + outerVariable);
}
}
}
In this example, `InnerClass` is defined within the `OuterClass`. It can access the private variable `outerVariable` of the outer class through its method `displayOuterVariable()`.
To create an instance of an inner class, you must first instantiate its outer class. Once you have an instance of the outer class, you can use it to create an instance of the inner class.
This is how you would create an instance of `InnerClass` and access its method:
class Main
{
public static void main(String[] args)
{
// Create instance of outer class
OuterClass outerInstance = new OuterClass();
// Using the instance of outer class, create instance of inner class
OuterClass.InnerClass innerInstance = outerInstance.new InnerClass();
// Now you can call inner class method
innerInstance.displayOuterVariable(); // This will print: Value of outerVariable in OuterClass is 1
}
}
Here, an instance of `OuterClass` called `outerInstance` is created first. Then, using `outerInstance`, we create an instance of `InnerClass` called `innerInstance`. With `innerInstance`, we can call the method `displayOuterVariable()`, which prints the value of `outerVariable`.
Inner Classes are utilized primarily for organizational purposes - they help make the code more readable and maintainable by grouping related classes together. Additionally, since inner classes can access the private members of the outer class, they can provide improved encapsulation. However, if used excessively, they can make the code harder to understand, so it's important to use them appropriately.