Java Inner Class :
What is an Inner Class?
Inner classes are also known as Nested class, is a class which is declared within another class.
Advantages of Inner Class:
- Inner class can access all the variables and methods of enclosing class including private members
- Useful for Interface Implementations used by enclosing class
- Fine control over interface implementation
Types of Inner Classes:
There are 4 types of Inner Classes,
- Static Nested Class
- Member Inner Class
- Method Local-Inner Class
- Anonymous Inner Class
Static Nested Class:
A class within another class is known as Static Nested Class
Member Inner Class:
Class created within a class but outside methods
Method Local-Inner Class:
Class created within a methods
Anonymous Inner Class:
Class created for implementing interface or extending class
Today, In this article we are going to see an example of Static Nested Class i.e. Class within a class
Syntax for creating object for Inner Class,
OuterClassName.InnerClassName ObjectofInnerClass = OuterClassObject.new InnerClassName();
This syntax may look like complex one, But once we are through with the code we can understand it easily.
public class InnerExample { String text1="Outerclass Text"; private String outerText = "Accessing Outerclass Text"; private void printText() { System.out.println(text1); } //Inner Class class Inner { public void printOuterText() { System.out.println("This is Inner Class Text"); System.out.println(outerText); } } public static void main(String args[]) { System.out.println("Outer Class Printing"); InnerExample innerexample = new InnerExample(); innerexample.printText(); System.out.println("Now Printing from Inner Class"); InnerExample.Inner inner = innerexample.new Inner(); //Inner Class Object Creation inner.printOuterText(); } }
In this code, We have declared private method and a private variable in the outerclass and that has been accessed by the Inner class.
OuterClassName.InnerClassName ObjectofInnerClass = OuterClassObject.new InnerClassName();
Creating object for Inner class,
InnerExample.Inner inner = innerexample(OuterclassObject).new Inner();