将枚举视为类中的常规财产

时间:2019-04-26 15:24:38

标签: java enums getter-setter

我有一个包含多个属性的类,其中一个是enum

public class Car {

    private String manufacturer;
    private int power;

    public enum Color {
        RED("red"),
        BLUE("blue"),
        GREEN("green");

        private final String value;

        Color(final String value) {
            this.value = value;
        }

        public String getValue() {
            return value;
        }
    }

    public String getManufacturer() {
        return manufacturer;
    }

    public void setManufacturer(String manufacturer) {
        this.manufacturer = manufacturer;
    }

    public int getPower() {
        return power;
    }

    public void setPower(int power) {
        this.power = power;
    }

    public Car(String manufacturer, int power, Color color) {
        this.manufacturer = manufacturer;
        this.power = power;
//        Color(color); // Calling constructor, but --> ERROR: cannot find symbol
    }

    @Override
    public String toString() {
        return "Car{" + "manufacturer=" + manufacturer + ", power=" + power + '}'; // TODO add color
    }

}

我将该类放入列表中,并填充一些值:

List<Car>  car = Arrays.asList(
          new Car("Mazda", 95, Car.Color.BLUE),
          new Car("Toyota", 110, Car.Color.RED),
          new Car("Honda", 85, Car.Color.GREEN)
  );

我想像普通的DTO一样使用该类,并带有其getter和setter:

System.out.println(car.get(0));

但是我的情况只有这样:

Car{manufacturer=Mazda, power=95}

因此缺少color属性。

如何使用enum类型作为班级的常规属性?

2 个答案:

答案 0 :(得分:2)

您可以像使用Java中的其他任何类型一样使用枚举类型。只需尝试:

private String manufacturer;
private int power;
private Color color;  // here is the property of enum type

....

public Car(String manufacturer, int power, Color color) {
    this.manufacturer = manufacturer;
    this.power = power;
    this.color = color;
}

Car newCar = new Car("manufacturer", 150, Color.RED);

答案 1 :(得分:0)

我个人将枚举保存在自己的文件中(出于可读性考虑),并将枚举作为类车中的成员变量。

然后在您的枚举文件中放入这样的toString函数

   public String toString()
   {
        String returnValue = "";

        switch (this)
        {
           case RED:
            returnValue = "Red";
            break;
           case BLUE:
            returnValue = "Blue";
            break;
        }

        return returnValue;
    }

然后在您的toString中开车:

return "Car{" + "manufacturer=" + manufacturer + ", power=" + power + " Colour = " + colour.toString() + "}";

带有颜色的颜色是此类中枚举的成员变量。