【问题标题】:How to pass an enum value to a constructor如何将枚举值传递给构造函数
【发布时间】:2013-11-19 10:47:38
【问题描述】:
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 = ....;
}

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

谁能帮忙?

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

【问题讨论】:

    标签: java constructor enums


    【解决方案1】:

    像这样的

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

    例如:

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

    然后在构造函数内部

     this.category = categ;
    

    【讨论】:

      【解决方案2】:

      您可以直接发送枚举,也可以发送一个字符串并使用 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);
      }
      

      【讨论】:

        【解决方案3】:
        public Book(String title, int code, List<String> authors, String publisher, int year, Category categ){
                // ...
                this.category = categ;
        }
        

        然后调用

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

        【讨论】:

          【解决方案4】:

          这里是枚举常量值的简单赋值给枚举变量。

          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);
          

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

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

          this.category = categ;
          

          【讨论】:

            猜你喜欢
            • 2012-10-29
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2014-07-14
            • 2019-12-12
            • 1970-01-01
            • 2020-02-14
            相关资源
            最近更新 更多