1.Can a constructor in Java be private?
2.In what scenarios we will use private constructor in java.
3.What will happen if we extends a class which is having private constructor.
Singleton Design pattern:
Output:
- 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.
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
Singleton Design pattern:
- package com.privateConstructorSingleTon;
- public class SingletonClass {
- private static SingletonClass object;
- private SingletonClass ()
- {
- System.out.println("Singleton(): Private constructor invoked");
- }
- public static SingletonClass getInstance()
- {
- if (object == null)
- {
- System.out.println("getInstance(): First time getInstance was called and object created !");
- object = new SingletonClass ();
- }
- return object;
- }
- }
- package instanceofjava;
- public class SingletonObjectDemo {
- public static void main(String args[]) {
- SingletonClass s1= SingletonClass .getInstance();
- SingletonClass s2= SingletonClass .getInstance();
- System.out.println(s1.hashCode());
- System.out.println(s2.hashCode());
- }
- }
Output:
- getInstance(): First time getInstance was called and object created !
- Singleton(): Private constructor invoked
- 655022016
- 655022016
No comments