This week's book giveaway is in the Performance forum.
We're giving away four copies of The Java Performance Companion and have Charlie Hunt, Monica Beckwith, Poonam Parhar, & Bengt Rutisson on-line!
See this thread for details.
Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

private/public constructor

 
aymane chetibi
Ranch Hand
Posts: 175
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What the difference between a private and public constructure.
both are compile and run correctly .


thank you
regards,
 
Mark Spritzler
ranger
Sheriff
Posts: 17278
6
IntelliJ IDE Mac Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Naseem Khan
Ranch Hand
Posts: 809
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
wise owen
Ranch Hand
Posts: 2023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
    Posts: 175
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Thank you all!

    regards,
     
    • Post Reply
    • Bookmark Topic Watch Topic
    • New Topic