Here we will learn how to create singleton class in java.
Firstly we need to know about singleton class.
Singleton Class
A class which can have only one instance.
The program for creating singleton class.
/** * */ package org.mani.javaexamples; /** * @author mani * */ public class SingletonClassExample { private static SingletonClassExample newObj; static{ newObj=new SingletonClassExample(); } private SingletonClassExample() { } public static SingletonClassExample getNewObj() { return newObj; } public void test() { System.out.println("hi...its working"); } public static void main(String[] args) { SingletonClassExample sobj=getNewObj(); sobj.test(); //SingletonClassExample sobj2=new SingletonClassExample(); //sobj2.test(); } }
Here when you run this program,you get output hi....its working.
I have commented out two lines in main method.If I uncomment that whether the code will compile or not??
Since we are having main in the same class,it will compile properly since constructor is visible here.
But when you will try to invoke this line of code from any other class,
it wont compile.
I have commented out two lines in main method.If I uncomment that whether the code will compile or not??
Since we are having main in the same class,it will compile properly since constructor is visible here.
But when you will try to invoke this line of code from any other class,
it wont compile.