aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Private Constructor Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Private Constructor" Watch "Private Constructor" New topic
Author

Private Constructor

prawith thowphant
Greenhorn

Joined: Sep 20, 2001
Posts: 5
hello my friends, can I declare the class's constructors as private?
Scott Xia
Greenhorn

Joined: Aug 20, 2001
Posts: 20
private constructor is OK
as i know the constructor of java.lang.Math is private
prawith thowphant
Greenhorn

Joined: Sep 20, 2001
Posts: 5
thank you scott. but what happen when I declare like this?
Scott Xia
Greenhorn

Joined: Aug 20, 2001
Posts: 20
if you declare private constructor but no other no-private constructors ,then the class can not instantized.
marilyn murphy
Ranch Hand

Joined: Aug 28, 2001
Posts: 84
... then the class cannot be instantiated.
Jose Botella
Ranch Hand

Joined: Jul 03, 2001
Posts: 2120
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.


SCJP2. Please Indent your code using UBB Code
Ragu Sivaraman
Ranch Hand

Joined: Jul 20, 2001
Posts: 464
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

Joined: Sep 22, 2001
Posts: 2579

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

Joined: Aug 28, 2001
Posts: 84
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Private Constructor