2

Statement is here

There is a statement "The enum constructor can be invoked outside of enum." in JAVA SE:Programming Complete Course. I know enum constructors can either have private or default access modifier. When it's private we can't access enum constructor outside of the enum. We may access enum constructor outside of enum when it has default access modifier. But I couldn't find any example of how to access enum constructors outside of the enum. Could you please give an example for this case?

2
  • You can't. The statement is simply wrong. Enum constructors without a modifier are implicitly private. Commented Apr 27, 2021 at 12:57
  • It's wrong. Those 3 entries (hot, warm, cold) are the only instances. An enum represents a finite set of possible instances. If you could instantiate more of them arbitrarily then the whole idea is pointless. Commented Apr 27, 2021 at 12:58

2 Answers 2

5

From the language specification:

It is a compile-time error if a constructor declaration in an enum declaration is public or protected (§6.6).

...

In an enum declaration, a constructor declaration with no access modifiers is private.

So, enum constructors are always private: you can't invoke an enum constructor outside the enum itself; and you can only invoke another a constructor via this(...) as the first statement of one of the enum constructors, not as new MyEnumType(...).

Sign up to request clarification or add additional context in comments.

2 Comments

So there is no difference between defining constructor default or private right?
"In an enum declaration, a constructor declaration with no access modifiers is private." It is redundant to declare it private, but there is no semantic difference.
2

From Java Documentation:

https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html

The constructor for an enum type must be package-private or private access. It automatically creates the constants that are defined at the beginning of the enum body. You cannot invoke an enum constructor yourself

Package-private means with no access modifier, but in this case the Enum constructor implicitly will still have only private access.

3 Comments

What is the meaning of the package-private? We can't already access enum constructor's outside of the enum.
Package-private means with no access modifier, but in this case the constructor implicitly will still have only private access @Semih Ataman.
:) You can thanx by pointing answer as useful @Semih Ataman

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.