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 trial

Java Java Objects Creating the MVP Getting Started

Is a constructor always public?

Is a constructor always public?

Thank you :)

1 Answer

Steven Parker
Steven Parker
231,184 Points

It'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.

so I know by convention the constructor name matches the class, but had that NOT been the case, then would it be this?

class object = new constructor();
// example
Car bmw = new Car();

What's a singleton class? I'm gonna need the Java for newbies answer 🙂

Steven Parker
Steven Parker
231,184 Points

The 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.