Wrting a class within another is allowed in Java. The class written within is called nested class, and the class that holds the inner class is called the outer class.
1. Nested Classes
class Outer_Demo {
class Inner_Demo {
}
}
Nested classes are divided into two types
- Non-static nested classes: The are the non-static members of a class.
- Static nested classes: These are the static members of a class.
2. Inner Classes(Non-static Nested Classes)
Inner classes are a security mechanism in Java. We know a class cannot be associated with the access modifier private, but if we have the class as a member of other class, then inner class can be made private.And this is also used to access the private members of a class.
Inner classes are of three types depending on how and where you define them.
- Inner class
- Method-local Inner Class
- Anonymous Inner Class
- Accessing the Private Members: 内部类可以访问外部类的私有成员
// 实例化一个内部类(必须要有其对应的外部类实例存在)
Outer_Demo outer = new Outer_Demo();
Outer_Demo.Inner_Demo inner = outer.new Inner_Demo()
- Method-local Inner Class:
在方法里定义的内部类是一个局部类型,只能在函数内使用。即一个method-local inner class只能在函数内部实例化。
- Anonymous Inner Class:
对于匿名内部类,其声明和初始化是同时进行的。其作用通常是为了重写某个方法
// 创建一个匿名内部类并初始化
AnonymousInner an_inner = new AnonymousInner() { // 创建一个匿名内部类,其实是创建了目标类的子类对象
@override
public void my_method() { // 重写基类方法
}
}
2. static nested class
静态内部类就像外部类的一个静态成员,可以无需实例化外部类就访问该静态内部类。就想静态成员一样,静态内部类不能访问外部类实例成员变量和方法。
class MyOuter {
static class Nested_Demo {
}
}