静态类只能作为内部类出现,一般用于Builder模式。
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("xx").build();
return outer;
}