Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

private & protected constructors  RSS feed

 
Anilkumar Ravinuthala
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
please let me know the conditions we should prefer private & protected constructors
 
Campbell Ritchie
Marshal
Posts: 55707
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you don't want the constructor called from outside their own class.
When you don't want other classes to be able to instantiate this class.

Example: the java.lang.Math class has a private constructor which makes it impossible to instantiate a Math object.
Example: Go through these fora with the "search" option until you find "singleton." A "singleton" should only have one instance; its constructor is private so it can only be instantiated from inside its own class, so only one instance is ever created.

A protected constructor only works when the superclass is hidden away in a different package. It then restricts constructor calls to classes in its own package (which you have hidden away) and its subclasses, presumably in the form "super(a, b, c);".
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!