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


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "private/public constructor" Watch "private/public constructor" New topic
Author

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
regards,
Mark Spritzler
ranger
Sheriff

Joined: Feb 05, 2001
Posts: 17250
    
    6

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.

Mark


Perfect World Programming, LLC - Two Laptop Bag - Tube Organizer
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.

Regards

Naseem.K


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!

    regards,
     
    Consider Paul's rocket mass heater.
     
    subject: private/public constructor