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 instance of the object, wherein you can handle the object creation inside the class only. In this example we are creating object by using static block.
package com.java2novice.algos; 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(); } }
Implementing Singleton class with getInstance() method
// Java program implementing Singleton class // with getInstance() method class Singleton { // static variable single_instance of type Singleton private static Singleton single_instance = null; // variable of type String public String s; // private constructor restricted to this class itself private Singleton() { s = "Hello I am a string part of Singleton class"; } // static method to create instance of Singleton class public static Singleton getInstance() { if (single_instance == null) single_instance = new Singleton(); return single_instance; } } // Driver Class class Main { public static void main(String args[]) { // instantiating Singleton class with variable x Singleton x = Singleton.getInstance(); // instantiating Singleton class with variable y Singleton y = Singleton.getInstance(); // instantiating Singleton class with variable z Singleton z = Singleton.getInstance(); // changing variable of instance x x.s = (x.s).toUpperCase(); System.out.println("String from x is " + x.s); System.out.println("String from y is " + y.s); System.out.println("String from z is " + z.s); System.out.println("\n"); // changing variable of instance z z.s = (z.s).toLowerCase(); System.out.println("String from x is " + x.s); System.out.println("String from y is " + y.s); System.out.println("String from z is " + z.s); } }
Output:
String from x is HELLO I AM A STRING PART OF SINGLETON CLASS String from y is HELLO I AM A STRING PART OF SINGLETON CLASS String from z is HELLO I AM A STRING PART OF SINGLETON CLASS String from x is hello i am a string part of singleton class String from y is hello i am a string part of singleton class String from z is hello i am a string part of singleton class
[crayon-679fd4a9b879f290323930/] [crayon-679fd4a9b87aa056623899/] Output: Adding: 3 Adding: 32 Adding: 54 Adding: 89 3 32 54 89…
You are given an array of numbers. Find out the array index or position where…
1) Using StringBuffer class In this method, we use reverse() method of StringBuffer class to reverse the…
1) Using replaceAll() Method. In the first method, we use replaceAll() method of String class…
Singly Linked Lists are a type of data structure. It is a type of list.…