Java Inner Classes
In this chapter, we will learn about Java inner classes.
In Java, one class can nest another class. The syntax is as follows:
class OuterClass { // 外部类
// ...
class NestedClass { // 嵌套类,或称为内部类
// ...
}
}
To access the 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 often referred to as an inner class.
Since the inner class is nested in the outer class, you must first instantiate the outer class, and then create an object of the inner class.
Example
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
Inner classes can be modified with private or protected. If you do not want the inner class to be accessed from outside the outer class, you can use the private modifier:
Example
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);
}
}
In the above example, InnerClass is set as a private inner class, and executing it will report an error:
MyMainClass.java:12: error: OuterClass.InnerClass has private access in OuterClass
OuterClass.InnerClass myInner = myOuter.new InnerClass();
^
Static Inner Class
Static inner classes can be defined using the static keyword. For static inner classes, we do not need to create an outer class to access them; we can access them directly:
Example
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:Static inner classes cannot access members of the outer class.
Accessing Outer Class Members from an Inner Class
An advanced use of inner classes is that they can access the properties and methods of the outer class:
Example
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:
10Other Extensions
Java Objects and Classes