Pav*_*dis 3 java enums constructor
protected enum Category { Action, Fiction, Drama, Romance, SciFi, Poems, Kids }
Run Code Online (Sandbox Code Playgroud)
我创建了这个enum类型,现在我必须为我的类创建一个构造函数.
public Book(String title, int code, List<String> authors, String publisher, int year, Category categ){
this.title = title;
this.code = code;
this.authors = authors;
this.publisher = publisher;
this.year = year;
this.category = ....;
}
Run Code Online (Sandbox Code Playgroud)
我不明白我将如何向构造函数传递枚举类型的值.
有人可以帮忙吗?
我知道这是初学者的问题,但我似乎无法在任何地方找到答案.
像这样的东西
new Book( title, ........ ,Category.anyEnumConstant);
Run Code Online (Sandbox Code Playgroud)
例如:
Book book= new Book( title, ........ ,Category.Fiction);
Run Code Online (Sandbox Code Playgroud)
然后在构造函数内部
this.category = categ;
Run Code Online (Sandbox Code Playgroud)
您既可以发送枚举,也可以发送字符串并使用valueOf()来获取Enum.
解决方案1:发送枚举.
new Book(title, code, authors, publisher, year, Category.Action);
Run Code Online (Sandbox Code Playgroud)
在你的构造函数中,
public Book(String title, int code, List<String> authors, String publisher, int year, Category categ){
...
this.category = categ;
}
Run Code Online (Sandbox Code Playgroud)
解决方案2:发送一个字符串值并使用它valueOf()来获取它的枚举.
new Book(title, code, authors, publisher, year, "Action");
Run Code Online (Sandbox Code Playgroud)
在你的构造函数中,
public Book(String title, int code, List<String> authors, String publisher, int year, String categString){
....
this.category = Category.valueOf(categString);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12439 次 |
| 最近记录: |