Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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
218,812 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
218,812 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.