How to Make a Singleton Class in Java || Singleton Pattern Java

04:10

If you are reading this then, you should have knowledge about Design Patterns in programming languages. Because, Singleton Pattern is one of the types in design patterns.

Singleton Pattern in java means we have to make a class with which we can create only a single object, not more than one.

So, here i'm giving you the code of writing a java class
of which we can create only single object.

public class SingletonClass
{
  private static SingletonClass obj = null;
  private SingletonClass(){}
  public static SingletonClass getInst()
  {
    if(obj==null) {
     obj = new SingletonClass();
    }
    return obj;
  }
  protected static void show()
  {
   System.out.println(obj);
  }
  
}


public class mainClass
{
  public static void main(String[] args)
  {
    SingletonClass ref = SingletonClass.getInst();
    ref.show();
  }
  
}

if, you have any questions regarding this post you can write in comments, i'll appreciate that as per my knowledge. thanks for reading my post.

You Might Also Like

0 comments

If you have any questions or suggestions, you are free to ask, i will appreciate that and, i will try my best...

Check Out