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 Constructor is declared as private. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Constructor is declared as private." Watch "Constructor is declared as private." New topic

Constructor is declared as private.

Joy Vergis
Ranch Hand

Joined: Sep 14, 2009
Posts: 48
i have declared a constructor as private. The program compiles and executes also. PLease let me know in whiich possible conditions we cab have the class declared as public and constructor as private.

John Jai

Joined: May 31, 2011
Posts: 1776
I think when you want your class to be used by other classes in a different package without being able to create an object for your class
Seetharaman Venkatasamy
Ranch Hand

Joined: Jan 28, 2008
Posts: 5575

when you *dont want to create an object of a class in other class* by using that constructor which is marked as private. it is similar to any other method, if you marked a method as private, then you cant see the method outside the class.
fred rosenberger
lowercase baba

Joined: Oct 02, 2003
Posts: 11955

Private constructors are also commonly used in the Singleton design pattern (although there is some debate on whether this is a legitimate pattern or not).

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Don't get me started about those stupid light bulbs.
subject: Constructor is declared as private.
It's not a secret anymore!