eh3rrera / ocpj8-book

Study guide for the Oracle Certified Professional, Java SE 8 Programmer Exam (1Z0-809)
Other
129 stars 90 forks source link

Enumeration question #72

Closed zhengye1 closed 6 years ago

zhengye1 commented 6 years ago

one of the explanation for the question is following:

You can use the new operator inside an enum, but you cannot use the new operator to create a reference to an enum.

I get the second half of the statement, which means we cannot do this

enum Season{
   SPRING, SUMMER, AUTUMN, WINTER;
}

public class Test{
   public static void main(String[] args){
      Season s = new Season(); // Because constructor in Season is private
   }
}

But what is means

You can use the new operator inside an enum

and can you provide me an example for this?

eh3rrera commented 6 years ago

I was trying to create a tricky question, it doesn't have a special meaning.

I mean, an Enum can have fields, methods and constructors, and of course, you can use the new operator to instantiate the fields or other objects inside methods/constructors:

public enum MyEnum {
    ONE(1), TWO(2);

    private BigDecimal asBigDecimal;
    private List<String> list = new ArrayList<String>();

    MyEnum(int i) {
        asBigDecimal = new BigDecimal(i);
    }
}
zhengye1 commented 6 years ago

Thank you ~