wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes About private constructor... Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "About private constructor..." Watch "About private constructor..." New topic
Author

About private constructor...

Abimaran Kugathasan
Ranch Hand

Joined: Nov 04, 2009
Posts: 2066

It's said in the K&B's book,

Constructor can use any access modifiers, including private. (A private constructor means only code within the class itself can instantiate an object of that type, so if the private constructor class wants to allow an instance of the class to an instance created within the class


I don't have c clear understand in that bold para. And see the below coding....



makes a Compilation error as I expected [ClassA(int) has private access in ClassA]. What is the solution? Thanks in Advanced!


|BSc in Electronic Eng| |SCJP 6.0 91%| |SCWCD 5 92%|
Neha Daga
Ranch Hand

Joined: Oct 30, 2009
Posts: 504
this means that if the constructor of a class is private it can only be instantiated within that class and none of its subclass will be able to call that private constructor and hence none of the subclass can be instantiated with call to that private constructor.

In your code you can change the modifier of constructor from private to protected this way your subclass will be able too call that constructor.


SCJP 1.6 96%
Harpreet Singh janda
Ranch Hand

Joined: Jan 14, 2010
Posts: 317

This means that if you wants to create an instance of the class with private constructor, you have to provide a mean to initiate that class from within the class itself.

In your class you have to provide a static method which will return object of it's own class like




and you can use this class as:




Classes with private constructor are useful when you don't want a class to be extended by some other class Or when you want to create a class as singleton.

Abimaran Kugathasan
Ranch Hand

Joined: Nov 04, 2009
Posts: 2066

Thanks a lot Neha Daga. Thanks a lot Harpreet Singh janda, Great! Actually, I'm typing those questions, but explained it! Thanks....
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: About private constructor...
 
Similar Threads
Is my constructor doing more than I am aware of ?
How to pass values between classes?
Scope and classes/methods
Accessing class variables from another class
How to access another class having private constructor using it's static variavble ?