如何将枚举值传递给构造函数

时间:2013-11-19 10:47:38

标签: java constructor enums

protected enum Category { Action, Fiction, Drama, Romance, SciFi, Poems, Kids } 

我创建了这个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 = ....;
}

我不明白我将如何将构造函数传递给枚举类型的值。

有人可以帮忙吗?

我知道这是初学者的问题,但我似乎无法在任何地方找到答案。

4 个答案:

答案 0 :(得分:8)

像这样的东西

new Book( title, ........ ,Category.anyEnumConstant);

例如:

   Book book=  new Book( title, ........ ,Category.Fiction);

然后在构造函数

 this.category = categ;

答案 1 :(得分:5)

您既可以发送枚举,也可以发送字符串并使用valueOf()来获取枚举。

解决方案1:直接发送枚举。

new Book(title, code, authors, publisher, year, Category.Action);

并在您的构造函数中

public Book(String title, int code, List<String> authors, String publisher, int year, Category categ){
    ...
    this.category = categ;
}

解决方案2:发送字符串值并使用valueOf()从中获取枚举。

new Book(title, code, authors, publisher, year, "Action");

并在您的构造函数中

public Book(String title, int code, List<String> authors, String publisher, int year, String categString){
    ....
    this.category = Category.valueOf(categString);
}

答案 2 :(得分:1)

public Book(String title, int code, List<String> authors, String publisher, int year, Category categ){
        // ...
        this.category = categ;
}

然后致电

new Book(/* ... */, Category.Action)

答案 3 :(得分:0)

这是枚举常量值到枚举变量的简单分配。

String title= "somevalue";
int code = 1;
ArrayList<String> arrayList = new ArrayList<String>();
String publisher = "somevalue";
int year=2013;
Category categ = Category.Action;
Book book = new Book(title, code, arrayList, publisher, year, categ);

在Enums中,我们只使用枚举声明中声明的枚举对象常量。 实际上它们是你的枚举的对象。 这是一个链接,您可以在其中找到一个简单的示例来探索枚举。 http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html

在构造函数声明中,您只需像其他变量一样分配值。

this.category = categ;
相关问题