Soujanya
Soujanya

Reputation: 287

How to load Enum from java object

I am working on Java. Please check my code below:

TestEnum.java

public class TestEnum
{
     public enum AccountState {
         NEW("new"), OLD("old")
     }
}

MyMain.java

public class MyMain
{
   public static void main(String args[])throws Exception {
      //working fine
      System.out.println(TestEnum.AccountState.NEW);

      // But When I create object for TestEnum by using new ,It's throw error  message

      System.out.println(new TestEnum().AccountState.NEW);
   }
}

I am getting below error

AccountState cannot be resolved or is not a field Any one correct me what I did wrong in my code.

Upvotes: 2

Views: 285

Answers (2)

nano_nano
nano_nano

Reputation: 12523

there is no need to create a new TestEnum object:

System.out.println(TestEnum.AccountState.NEW);

your enum is static.

Beside of that I miss something like that:

  public enum AccountState {
    NEW("new"), OLD("old");
    private final String code;

    /**
     * @param code
     */
    private AccountState(final String code) {
      this.code = code;
    }


    @Override
    public String toString() {
      return code;
    }
  }

otherwise you cant declare an enum with string value constructor.

Upvotes: 1

Andy Turner
Andy Turner

Reputation: 140328

(Just adding some more information on top of @StefanBeike's answer).

According to JLS §8.9:

Nested enum types are implicitly static. It is permissible to explicitly declare a nested enum type to be static.

So you can reference it using:

System.out.println(TestEnum.AccountState.NEW);

Upvotes: 2

Related Questions