为什么此代码在没有边界类型参数化的情况下可以工作?

时间:2019-07-12 12:12:53

标签: java bounded-types

我试图理解有界类型参数,希望这段代码将返回编译时错误。但是这段代码可以正常工作。我想念什么?

根据我对Bounded类型参数的理解,Pizza中的抽象Builder类应声明为abstract static class Builder<T extends Builder<T>>,以使addTopping(..)链接正常工作。

我想念什么?

import java.util.EnumSet;
import java.util.Set;
import java.*;

abstract class Pizza {

  public enum Toppings {
    CHICKEN, MUSHROOM, PEPPER
  };

  final Set<Toppings> toppings;

  abstract static class Builder<T> {
    EnumSet<Toppings> toppings = EnumSet.noneOf(Toppings.class);;

    public T addTopping(Toppings t) {
      toppings.add(t);
      return self();
    }

    abstract Pizza build();

    abstract T self();

  }

  Pizza(Builder<?> b) {
    toppings = EnumSet.noneOf(Toppings.class);
    for (Toppings t : b.toppings)
      toppings.add(t);
  }

  public void printToppings() {
    System.out.println("Toppings are : ");
    for (Toppings t : toppings)
      System.out.print(t + " ");
  }
}

class NYPizza extends Pizza {

  private final boolean sauceInside;

  private NYPizza(Builder builder) {
    super(builder);
    sauceInside = builder.sauceInside;

  }

  static class Builder extends Pizza.Builder<Builder> {
    private boolean sauceInside = false; // Default

    public Builder sauceInside() {
      sauceInside = true;
      return this;
    }

    @Override
    Builder self() {
      return this;
    }

    @Override
    public NYPizza build() {
      return new NYPizza(this);
    }
  }

}

public class HelloWorld {

  public static void main(String[] args) {

    NYPizza.Builder b = new NYPizza.Builder();
    NYPizza p = b.addTopping(Pizza.Toppings.MUSHROOM).addTopping(Pizza.Toppings.CHICKEN).sauceInside().build();
    p.printToppings();
  }
}

0 个答案:

没有答案