Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Query on constructor

 
abin joy
Ranch Hand
Posts: 35
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can a constructor of a class be marked as private?
 
Ulf Dittmer
Rancher
Pie
Posts: 42966
73
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What happened when you tried it?
 
Santhi Bharath
Ranch Hand
Posts: 75
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
up to my knowledge you can mark as private.but,you can't instantiate that class.this is mainly used in singleton creation
 
venkatesh badrinathan
Ranch Hand
Posts: 77
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you have two cases here.
1)you can instantiate the class with it.
2)but, you either cannot extend the class nor instantiate it outside the class

i think this helps you..??
 
venkatesh badrinathan
Ranch Hand
Posts: 77
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
sorry, i should have told like,
you can instantiate it within the same class(ie. class with constructor marked as private)
 
Janardan Kelkar
Ranch Hand
Posts: 72
Eclipse IDE Firefox Browser Suse
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Since a constructor (although private) has been defined in the superclass, the base class cannot access it, hence even though the base class has a default constructor, it cannot make an implicit call to the constructor in the superclass (since it is private). Any constructor must have a call to a constructor in the supercalss as its first statement.
So effectively what we are doing is trying to access the private member of the superclass which is illegal in the first place.
The class by itself can be instantiated with a private constructor, there are no problems.
 
Campbell Ritchie
Sheriff
Pie
Posts: 47258
52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, you can have a private constructor. It is used for two main reasons:
  • To prevent the class being instantiated at all.
  • To restrict the class from being instantiated outside a factory method. Do a search for singleton pattern, which uses that trick.
  • If you have a class which only has private constructors, it is impossible to inherit from that class, so you ought to mark the class "final" as well.
     
    I agree. Here's the link: http://aspose.com/file-tools
    • Post Reply
    • Bookmark Topic Watch Topic
    • New Topic