静态类只能作为内部类出现,一般用于Builder模式。

    1. public class Outer {
    2. private String name;
    3. private int age;
    4. public static class Builder {
    5. private String name;
    6. private int age;
    7. public Builder(int age) {
    8. this.age = age;
    9. }
    10. public Builder withName(String name) {
    11. this.name = name;
    12. return this;
    13. }
    14. public Builder withAge(int age) {
    15. this.age = age;
    16. return this;
    17. }
    18. public Outer build() {
    19. return new Outer(this);
    20. }
    21. }
    22. private Outer(Builder b) {
    23. this.age = b.age;
    24. this.name = b.name;
    25. }
    26. }


    优点在于,调用的时候不需要实例化外部。

    1. public Outer getOuter()
    2. {
    3. Outer outer = new Outer.Builder(2).withName("xx").build();
    4. return outer;
    5. }