Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Private Constructor

 
prawith thowphant
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hello my friends, can I declare the class's constructors as private?
 
Scott Xia
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
private constructor is OK
as i know the constructor of java.lang.Math is private
 
prawith thowphant
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thank you scott. but what happen when I declare like this?
 
Scott Xia
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
if you declare private constructor but no other no-private constructors ,then the class can not instantized.
 
marilyn murphy
Ranch Hand
Posts: 84
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
... then the class cannot be instantiated.
 
Jose Botella
Ranch Hand
Posts: 2120
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
the class can not be instantiated from outside. But it could be useful invoking it from inside: because sometimes only an instance of a class is needed a static method can invoke the constructor only once.
 
Ragu Sivaraman
Ranch Hand
Posts: 464
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Private constructors are little weird
They allow instantiation inside of the class
But outside of the class or subclassing will yield a compilation error
Ragu
 
Manish Hatwalne
Ranch Hand
Posts: 2596
Android Firefox Browser Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
private/protected constructors are very important and they are useful in many ways in OOP. Many of the Java classes use them, the idea is to have greater control on 'how a new instance will be created', the ones having such constructors typically have factory methods (you may want to read book - Design Patterns) to create an instance. One class I can think of now which has such a constructor is URLConnection, among many others.
You can't do new URLConnection(), but can get a reference to it by method openConnection() of URL class.
[This message has been edited by Manish Hatwalne (edited September 22, 2001).]
 
marilyn murphy
Ranch Hand
Posts: 84
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Speaking of patterns, private constructors are also useful in creating Singletons.

I am sorry that I was not clear in my previous message. I was only correcting the terminology, not actually stating that the class cannot be instantiated. Of course the class can instantiate itself.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic