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 (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,860 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.