Enum class initialization in Java

后端 未结 2 1004
有刺的猬
有刺的猬 2020-12-06 15:19

In Java we can do the following to initialize class and call method inside that class:

public class MyClass {
  public String myClassMethod() {
    return \"         


        
2条回答
  •  北海茫月
    2020-12-06 16:11

    It's a simple implementation of the Singleton pattern, relying on the mechanisms of how Enum's work.

    If you use MyEnumClass.INSTANCE a second time, you'll get the same object instance.

    In contrast, new MyClass(); will create a new object.

    See also discussion here:

    What is the best approach for using an Enum as a singleton in Java?

    There would possibly be more to learn by reading Java Language Spec Section 8-9

提交回复
热议问题