Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialMark Chesney
11,747 PointsIs a constructor always public?
Is a constructor always public?
Thank you :)
1 Answer
Steven Parker
231,184 PointsIt's uncommon, but possible to to have private (or protected) constructors. But a private constructor can only be called from within the class itself, so a new instance could only be created by a class method.
This might be used by a singleton class, to insure that only one instance is ever created.
Mark Chesney
11,747 PointsMark Chesney
11,747 Pointsso I know by convention the constructor name matches the class, but had that NOT been the case, then would it be this?
What's a singleton class? I'm gonna need the Java for newbies answer 🙂
Steven Parker
231,184 PointsSteven Parker
231,184 PointsThe fancy-sounding name "singleton" just means that the class is designed to have only one instance. Restricting the constructor to a class method allows you to write code to guarantee a second instance is not created.