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 (Retired) Meet Objects Constructors

Adam Sawicki
Adam Sawicki
15,967 Points

Constructor Name

Hey,

Can i name constructor diffrently than name of class?

3 Answers

Jason Anders
MOD
Jason Anders
Treehouse Moderator 145,631 Points

The short answer... No. And like Thomas, I'm curious as to "Why you would want to?"

If you did, you probably wouldn't be able to tell a constructor from a method. Have a look at this brief mention in the Oracle Docs.

:dizzy:

Thomas Nilsen
Thomas Nilsen
14,957 Points

I don't know why you'd want to, but you can have a method that returns a new instance of the class like this:

class A {

    //Default constructor
    public A () {}


    public static A B() {
        return new A();
    }

    public void print() {
        System.out.println("hello");
    }
}

class Test {
    public static void main(String[] args) {
        A a2 = A.B();
        A a1 = new A();

        a2.print();
        a1.print();

    }
}
thehuskyena
thehuskyena
1,792 Points

No, the name of the constructor must always be equal to the name of the class.