wood burning stoves*
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
Author

Constructor is declared as private.

Joy Vergis
Ranch Hand

Joined: Sep 14, 2009
Posts: 45
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
Bartender

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
Bartender

Joined: Oct 02, 2003
Posts: 11175
    
  16

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
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Constructor is declared as private.
 
Similar Threads
Extending a class with private constructor
Anonymous class
default constructor access
modifiers for constructors
about default constructor