» » » Can we create private constructor in java

1.Can a constructor in Java be private?
  • Yes we can declare private constructor in java.
  • If we declare constructor as private we can not able to create object of the class.
  • In singleton design pattern we use this private constructor. 

private constructor in java example program


 2.In what scenarios we will use private constructor in java.

  •  Singleton Design pattern
  • It wont allow class to be sub classed.
  • It wont allow to create object outside the class.
  • If All Constant methods is there in our class we can use private constructor.
  • If all methods are static then we can use private constructor.



 3.What will happen if we extends a class which is having private constructor.

  •  If we try to extend a class which is having private constructor compile time error will come.
  • Implicit super constructor is not visible for default constructor. Must define an explicit constructor

private constructor in java


Singleton Design pattern:


  1. package com.privateConstructorSingleTon;
  2.  
  3. public class SingletonClass {

  4. private static SingletonClass object;
  5.  
  6. private SingletonClass ()
  7. {
  8.         System.out.println("Singleton(): Private constructor invoked");
  9. }
  10.  
  11. public static SingletonClass getInstance()
  12. {
  13.  
  14. if (object == null)
  15. {
  16.  
  17. System.out.println("getInstance(): First time getInstance was called and object created !");
  18. object = new SingletonClass ();
  19.  
  20.  }
  21.  
  22. return object;
  23.  
  24. }
  25.  
  26. }
     



  1. package instanceofjava;
  2.  
  3. public class SingletonObjectDemo {

  4. public static void main(String args[]) {
  5.  
  6.      SingletonClass s1= SingletonClass .getInstance();
  7.      SingletonClass s2= SingletonClass .getInstance();
  8.      System.out.println(s1.hashCode());
  9.      System.out.println(s2.hashCode());
  10.  
  11. }
  12. }

Output:

  1. getInstance(): First time getInstance was called and object created !
  2. Singleton(): Private constructor invoked
  3. 655022016
  4. 655022016

Instance Of Java

We will help you in learning.Please leave your comments and suggestions in comment section. if you any doubts please use search box provided right side. Search there for answers thank you.
«
Next
Newer Post
»
Previous
Older Post

No comments

Leave a Reply

Select Menu