File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes private/public 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/public constructor" Watch "private/public constructor" New topic

private/public constructor

aymane chetibi
Ranch Hand

Joined: Apr 12, 2006
Posts: 175
What the difference between a private and public constructure.
both are compile and run correctly .

thank you
Mark Spritzler

Joined: Feb 05, 2001
Posts: 17276

Well it depends on if you want to use it outside of the class with the "new" statement.

so I can use

but you can't get this to compile

Because the constructor that takes an int is private.


Perfect World Programming, LLC - iOS Apps
How to Ask Questions the Smart Way FAQ
Naseem Khan
Ranch Hand

Joined: Apr 25, 2005
Posts: 809
If u don't want any other class to make an instance of ur class, declare all constructors private.
Very same wat Singleton design pattern do.

Whereas any class in any package can call public constructors.



Asking Smart Questions FAQ - How To Put Your Code In Code Tags
wise owen
Ranch Hand

Joined: Feb 02, 2006
Posts: 2023
Private constructor:

Private constructors prevent a class from being explicitly instantiated by callers.
There are a few common cases where a private constructor can be useful :
  • classes containing only static utility methods
  • classes containing only constants
  • type safe enumerations
  • singletons

  • aymane chetibi
    Ranch Hand

    Joined: Apr 12, 2006
    Posts: 175
    Thank you all!

    I agree. Here's the link:
    subject: private/public constructor
    It's not a secret anymore!