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
- package inheritanceInterviewPrograms;
- public class A {
- private A(){
- }
- public static void main(String args[]){
- A s= new A();
- }
- }
- package inheritanceInterviewPrograms;
- // www.instanceofjava.com
- public class B {
- public static void main(String [] args){
- A obj= new A();// Compile time error
- }
- }
- To understand real use of private constructor please check Singleton Design Pattern in java
No comments