Please disable adblock to view this page.

← Go home

Singleton snippet (Java)

May 10, 2016
Published By : Pratik Kataria
Categorised in:

public class singleton {

	private static singleton obj;

	
	private singleton(){
		System.out.println("Constructor is called only once.");
	}
	
	public static singleton getInstance(){
		if(obj == null){
			obj = new singleton();
		}
		return obj;
	}

	
	public int add(int i, int j){
		return (i + j);
	}
	
	public int sub(int i, int j){
		return (i-j);
	}
	
	public static void main( String [] args){
		
		singleton obj1 = singleton.getInstance();		
		singleton obj2 = singleton.getInstance();
		singleton.getInstance();
		singleton.getInstance();
		singleton.getInstance();
		
		// 'n' number of object creation won't call constructor 'n' times. This is singleton feature.
		
		System.out.println(singleton.getInstance().add(5, 6));	//it is object.function() call
		
	}
	
}

Output:

Constructor is called only once.
11

View Article Page
Download

Pratik Kataria is a budding programmer, web designer and developer.