Java Articles

Submit Article
Home » Articles » Java » FundamentalRSS Feeds

Private Constructor

Posted By: Josephine Gomez     Category: Java     Views: 9391

This article explains about private constructor in java with example.

Private constructors prevent a class from being explicitly instantiated by callers. private constructor are used to create Sinleton class. It can be invoked by code in the same class.

Syntax of Private Constructor

class clsName
     // Variable declaration
     private clsName()

     // Methods

clsName is a valid identifier in java. It is a class name.

Example of Private Constructor

Example 1 : Program that illustrates private constructor use in java 

public class SingletonObject
    private SingletonObject()
        // no code

    public static SingletonObject getObject()
      // we can call this constructor
      if (ref == null) 
          ref = new SingletonObject();
      return ref;

    private static SingletonObject ref;

public class PrivateVariableDemo
  public static void main(String args[])
  SingletonObject sObj = SingletonObject.getSingletonObject();


Didn't find what you were looking for? Find more on Private Constructor Or get search suggestion and latest updates.

Josephine Gomez
Josephine Gomez author of Private Constructor is from Wichita, United States.
View All Articles

Please enter your Comment

  • Comment should be atleast 30 Characters.
  • Please put code inside [Code] your code [/Code].

No Comment Found, Be the First to post comment!