What is a Private Constructor?

Author Topic: What is a Private Constructor?  (Read 4093 times)

Offline beingchinmayTopic starter

  • Trade Count: (0)
  • Jr. Member
  • **
  • Thank You 1
  • Posts: 73
  • Karma: 0
  • Gender: Male
  • I am Chinmay
    • Modular Kitchen Designer
What is a Private Constructor?
« on: 03-06-2017, 05:09:09 »
 Used to prevent the user to instantiate the class directly.
 Used to prevent the creation of instances of a class when there are no instance fields or methods
 A private constructor is a special instance constructor.
 It is commonly used in classes that contain static members only.
 If a class has one or more private constructors and no public constructors, then other classes (except nested classes) are not allowed to create instances of this class.
 Note that if you don't use an access modifier with the constructor it will still be private by default.
 Private constructors are used to restrict the instantiation of object using 'new' operator.
 This type of constructors is mainly used for creating singleton object.
 Can use nested class (Inner Class) or static method to initialize a class having private constructor.
 Example of Private Constructor - Math class


Offline richardmsmith

  • Trade Count: (0)
  • Full Member
  • ***
  • Thank You 3
  • Posts: 221
  • Karma: 0
  • Gender: Male
    • Trucking App Solution
Re: What is a Private Constructor?
« Reply #1 on: 08-31-2018, 00:18:12 »
It is an special instance constructor. It is generally used in classes that contain static members only. If a class has one or more private constructors and no public constructors, other classes (except nested classes) cannot create instances of this class.

Offline greatshivam

  • Trade Count: (0)
  • Newbie
  • *
  • Thank You 0
  • Posts: 5
  • Karma: 0
Re: What is a Private Constructor?
« Reply #2 on: 02-24-2020, 05:46:45 »
The private constructor is useful in case we want to restrict the object creation. For example, Singleton pattern can be implemented using a private constructor.

Example-

public class Tester {
   private static Tester instance;
   private Tester(){}
 
   public static Tester getInstance(){
      if(instance == null){
         instance = new Tester();
      }
      return instance;
   }
 
   public static void main(String[] args) {
      Tester tester = Tester.getInstance();
      Tester tester1 = Tester.getInstance();
      System.out.println(tester.equals(tester1));
   } 
}

It will print the output as-

true

 

Related Topics

  Subject / Started by Replies Last post
0 Replies
1237 Views
Last post 12-28-2015, 00:24:57
by chinmay.sahoo
5 Replies
2695 Views
Last post 02-19-2016, 07:15:46
by Herstin
0 Replies
958 Views
Last post 09-07-2016, 05:27:55
by beingchinmay
0 Replies
3267 Views
Last post 01-17-2017, 00:35:49
by beingchinmay
5 Replies
3510 Views
Last post 05-23-2017, 01:02:02
by deekumar0203