Java Inner Classes
In this section, we will learn about Java's inner classes.
In Java, a class can be nested within another class, with the following syntax:
class OuterClass { // Outer class
// ...
class NestedClass { // Nested class, or inner class
// ...
}
}
To access an inner class, you can create an object of the outer class, and then create an object of the inner class.
There are two types of nested classes:
- Non-static inner class
- Static inner class
Non-static Inner Class
A non-static inner class is a class nested within another class. It has access to the members of the outer class and is commonly referred to as an inner class.
Since the inner class is nested within the outer class, you must first instantiate the outer class, and then create an object of the inner class.
Example
class OuterClass {
int x = 10;
class InnerClass {
int y = 5;
}
}
public class MyMainClass {
public static void main(String[] args) {
OuterClass myOuter = new OuterClass();
OuterClass.InnerClass myInner = myOuter.new InnerClass();
System.out.println(myInner.y + myOuter.x);
}
}
The output of the above example is:
15
Private Inner Class
An inner class can be declared with private or protected access. If you do not want the inner class to be accessible from outside the outer class, you can use the private modifier:
Example
class OuterClass {
int x = 10;
private class InnerClass {
int y = 5;
}
}
public class MyMainClass {
public static void main(String[] args) {
OuterClass myOuter = new OuterClass();
OuterClass.InnerClass myInner = myOuter.new InnerClass();
System.out.println(myInner.y + myOuter.x);
}
}
The above example, with InnerClass set as a private inner class, will result in an error:
MyMainClass.java:12: error: OuterClass.InnerClass has private access in OuterClass
OuterClass.InnerClass myInner = myOuter.new InnerClass();
^
Static Inner Class
A static inner class can be defined using the static keyword. With a static inner class, we do not need to create an instance of the outer class to access it; we can access it directly:
Example
class OuterClass {
int x = 10;
static class InnerClass {
int y = 5;
}
}
public class MyMainClass {
public static void main(String[] args) {
OuterClass.InnerClass myInner = new OuterClass.InnerClass();
System.out.println(myInner.y);
}
}
The output of the above example is:
5
Note: A static inner class cannot access members of the outer class.
Accessing Outer Class Members from Inner Class
An advanced use of inner classes is the ability to access the properties and methods of the outer class:
Example
class OuterClass {
int x = 10;
class InnerClass {
public int myInnerMethod() {
return x;
}
}
}
public class MyMainClass {
public static void main(String[] args) {
OuterClass myOuter = new OuterClass();
OuterClass.InnerClass myInner = myOuter.new InnerClass();
System.out.println(myInner.myInnerMethod());
}
}
The output of the above example is:
10
10