Oct 23, 2020 in JAVA
Q: How to create singleton class in java?

2 Answers

0 votes
Oct 23, 2020

How to create singleton class in java?

Singleton class means you can create only one object for the given class. You can create a singleton class by making its constructor as private so that you can restrict the creation of the object. Provide a static method to get an instance of the object, wherein you can handle the object creation inside the class only. In this example, we are creating an object by using a static block.

public class MySingleton {

 

    private static MySingleton myObj;

     

    static{

        myObj = new MySingleton();

    }

     

    private MySingleton(){

     

    }

     

    public static MySingleton getInstance(){

        return myObj;

    }

     

    public void testMe(){

        System.out.println(""Hey.... it is working!!!"");

    }

     

    public static void main(String a[]){

        MySingleton ms = getInstance();

        ms.testMe();

    }

}

🔗Reference: stackoverflow.com

🔗Source: Java Interview Questions and Answers

0 votes
Oct 6
Just use object.

object SomeSingleton

The above Kotlin object will be compiled to the following equivalent Java code:

public final class SomeSingleton {

   public static final SomeSingleton INSTANCE;

   private SomeSingleton() {

      INSTANCE = (SomeSingleton)this;

      System.out.println("init complete");

   }

   static {

      new SomeSingleton();

   }

}

This is the preferred way to implement singletons on a JVM because it enables thread-safe lazy initialization without having to rely on a locking algorithm like the complex double-checked locking.

Related questions

0 votes
May 4 in JAVA
0 votes
May 2 in JAVA
...