String model;
int year;
enum Color {GREEN, BLUE, RED};
double price;
颜色深浅;
public Car(String model, int year, Color shade, double price) {
this.model = model;
this.year = year;
this.shade= shade;
this.price = price;
}
这样可以吗?当我实际使用 main 方法创建对象时仍然给出错误。
最佳答案
此语法:this.Color = shade;
引用 Car
类中名为 Color
的实例字段。
但 Car
类中没有任何 Color
字段。
这个:
enum Color {GREEN, BLUE, RED};
是枚举类声明。
只需在 Car
中引入一个字段即可为其分配Color
:
public class Car {
String model;
int year;
Color color;
...
public Car(String model, int year, Color shade, double price) {
this.model = model;
this.year = year;
this.color = shade;
this.price = price;
}
}
关于java - 将 ENUM 类型分配给构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47486100/