Constructor in java:

  • Constructor is used to initialize class variables.
  • Constructor will be executed once per object and whenever object is created constructor will be called.




Private Constructor in java:

  • We can make constructor private, public , protected and default.
  • If we define a constructor as private means we are restricting a class to create object  outside of the class.
  • A class having private constructor does not allow user to create object outside.
  • In singleton Design pattern we will use private constructor to restrict object creation


  1. package inheritanceInterviewPrograms;
  2.  
  3. public class A {
  4.   
  5.   private A(){
  6.        
  7.        
  8.    }
  9.  
  10. public static void main(String args[]){ 
  11.    
  12.       A s= new A();
  13.   }
  14.  
  15. }

  1. package inheritanceInterviewPrograms;
  2. //  www.instanceofjava.com
  3.  
  4. public class B {
  5.     
  6. public static void main(String [] args){
  7.      
  8.     A obj= new A();// Compile time error
  9.    
  10.  
  11. }
  12. }


private Constructor example

Instance Of Java

We are here to help you learn! Feel free to leave your comments and suggestions in the comment section. If you have any doubts, use the search box on the right to find answers. Thank you! 😊
«
Next
Newer Post
»
Previous
Older Post

No comments

Leave a Reply

Select Menu