Can we have a constructor private in java?

Java 8Object Oriented ProgrammingProgramming

A constructor is used to initialize an object when it is created. It is syntactically similar to a method. The difference is that the constructors have same name as their class and, have no return type.

There is no need to invoke constructors explicitly these are automatically invoked at the time of instantiation.

Access specifiers/modifiers allowed with constructors

Modifiers public, protected and, private are allowed with constructors.

We can use a private constructor in a Java while creating a singleton class. The Singleton's purpose is to control object creation, limiting the number of objects to only one. Since there is only one Singleton instance, any instance fields of a Singleton will occur only once per class, just like static fields. Singletons often control access to resources, such as database connections or sockets.

Accessing the private constructor

To access a private constructor (One way to do so) define a public and static method which creates and returns an object of the class (with private constructor).

Now you can get the instance by invoking this method.

Example

In the following Java program, we have a class with name Student whose constructor is private.

In the Student class we have a method with name getInstance() which is both public and static. This method creates an object of the Student class and returns it.

From another class we are invoking this (getInstance()) method and with the obtained instance/object we are calling the display() method of the Student class.

 Live Demo

class Student{
   private String name;
   private int age;
   private Student(){
      this.name = "Raju";
      this.age = 20;
   }
   public void display(){
      System.out.println("Name of the Student: "+this.name );
      System.out.println("Age of the Student: "+this.age );
   }
   public static Student getInstance() {
      Student object = new Student();
      return object;
   }
}
public class PrivateConstructorExample{
   public static void main(String args[]) {
      Student obj = Student.getInstance();
      obj.display();
   }
}

Output

Name of the Student: Raju
Age of the Student: 20
raja
Published on 03-Jul-2019 16:05:31
Advertisements