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

Kevin Frostad
Kevin Frostad
3,483 Points

I was trying to give my GoKart constructor a name, but it won't allow me.. Why is this?

public GoKart color(String color){ mColor = color; }

1 Answer

Kevin Faust
Kevin Faust
15,353 Points

You can't "name" a constructor. Constructors only consist of the word "public" followed by your class name. Therefore:

public GoKart (String color) { 
mColor = color; 
}
Kevin Frostad
Kevin Frostad
3,483 Points

Ohh.. I thought I read somewhere that you could use multiple constructors for a single class. Like a constructor which returns an int in addition to one that returns a String. Guess I've misinterpreted it..

Kevin Faust
Kevin Faust
15,353 Points

Well you can create multiple constructors that take in different values. In the example you have above, you are taking in a String. You could also do this:

public GoKart (int number) { 
mNumber = number; 
}

And depending what you pass into the constructor, the approriate constrcutor will be called. But at the end of the day, they always have the same name. Just their parameter values can change

Kevin Frostad
Kevin Frostad
3,483 Points

I think I've gotten it right. So when you're declaring a method which takes a parameter, you don't need to give it a return type if it's declared in the parameter. Like you have to if its parameter holds nothing, like this:

public void nothing(); public something(String str, int number);

And since a constants name is also its type it has to hold something in its parameter? Or could it hold nothing even if it's type is not void?

Kevin Faust
Kevin Faust
15,353 Points

Constructors and methods are two different things. Constructors have no return type (like void, String, int, etc) whereas methods always have a return type (like void, String, int, etc). If you declare a method which takes a parameter, you have to always specify a return type no matter what. It's just that when we are dealing with constructors, we dont have to.

Also only construcotrs have the class name when naming constrcutors. It's mandatory. Such as the other examples above. If it's a method, you shouldn't include the class name.

Kevin Frostad
Kevin Frostad
3,483 Points

I see, thanks for clearing that up.