File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Query on constructor Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Query on constructor" Watch "Query on constructor" New topic

Query on constructor

abin joy
Ranch Hand

Joined: Jul 29, 2008
Posts: 35
Can a constructor of a class be marked as private?
Ulf Dittmer

Joined: Mar 22, 2005
Posts: 42965
What happened when you tried it?
Santhi Bharath
Ranch Hand

Joined: Jun 03, 2008
Posts: 75
up to my knowledge you can mark as private.but,you can't instantiate that class.this is mainly used in singleton creation

thanks and regards<br />Santhi Bharath<br />SCJP 5.0, SCWCD 5.0
venkatesh badrinathan
Ranch Hand

Joined: Aug 03, 2008
Posts: 77
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

Joined: Aug 03, 2008
Posts: 77
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

Joined: May 05, 2008
Posts: 72

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.

When the compiler's not happy, ain't nobody happy.
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46352
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:
    subject: Query on constructor
    It's not a secret anymore!