Nested class 有两种形式,非静态的和静态的:
class OuterClass {
...
static class StaticInnerClass {
...
}
class InnerClass {
...
}
}
访问规则
InnerClass
可以访问OuterClass
中的其他成员,甚至是private
的StaticInnerClass
只可以访问OuterClass
中的静态成员
使用场景
InnerClass
适用于,只被一个类使用(OuterClass
),同时逻辑比较内聚,值得被封装成类的场景。InnerClass
也可以被外部使用,但是初始化很罗嗦:
OuterClass outerObject = new OuterClass();
OuterClass.InnerClass innerObject = outerObject.new InnerClass();
StaticInnerClass
可以给外部使用。Effective Java 有一例子:
public class Outer {
private String name;
private int age;
public static class Builder {
private String name;
private int age;
public Builder(int age) {
this.age = age;
}
public Builder withName(String name) {
this.name = name;
return this;
}
public Builder withAge(int age) {
this.age = age;
return this;
}
public Outer build() {
return new Outer(this);
}
}
private Outer(Builder b) {
this.age = b.age;
this.name = b.name;
}
public Outer getOuter() {
Outer outer = new Outer.Builder(2).withName("Yang Liu").build();
return outer;
}
}
Shadowing
public class ShadowTest {
public int x = 0;
class FirstLevel {
public int x = 1;
void methodInFirstLevel(int x) {
System.out.println(x); // 函数参数中的 x
System.out.println(this.x); // 内部类的 x
System.out.println(ShadowTest.this.x); // 外部类的 x
}
}
public static void main(String... args) {
ShadowTest st = new ShadowTest();
ShadowTest.FirstLevel fl = st.new FirstLevel();
fl.methodInFirstLevel(23); // 输入分别是:23, 1, 0
}
}
参考: