Users Online

· Guests Online: 95

· Members Online: 0

· Total Members: 188
· Newest Member: meenachowdary055

Forum Threads

Newest Threads
No Threads created
Hottest Threads
No Threads created

Latest Articles

007 Java - private constructor example

Java – private constructor example

The use of private constructor is to serve singleton classes. A singleton class is one which limits the number of objects creation to one. Using private constructor we can ensure that no more than one object can be created at a time. We will see in the below example how to use private constructor for limiting the number of objects for a singleton class.

Example

package beginnersbook.com;
public class SingleTonClass {
   //Static Class Reference
   private static SingleTonClass obj=null;
   private SingleTonClass(){
      /*Private Constructor will prevent 
       * the instantiation of this class directly*/
   }
   public static SingleTonClass objectCreationMethod(){
	/*This logic will ensure that no more than
	 * one object can be created at a time */
	if(obj==null){
	    obj= new SingleTonClass();
	}
        return obj;
   }
   public void display(){
	System.out.println("Singleton class Example");
   }
   public static void main(String args[]){
	//Object cannot be created directly due to private constructor 
        //This way it is forced to create object via our method where
        //we have logic for only one object creation
	SingleTonClass myobject= SingleTonClass.objectCreationMethod();
	myobject.display();
   }
}

Output:

Singleton class Example

Comments

No Comments have been Posted.

Post Comment

Please Login to Post a Comment.

Ratings

Rating is available to Members only.

Please login or register to vote.

No Ratings have been Posted.
Render time: 0.78 seconds
10,259,309 unique visits