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 trialKevin Frostad
3,483 PointsI 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
15,353 PointsYou 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
3,483 PointsKevin Frostad
3,483 PointsOhh.. 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
15,353 PointsKevin Faust
15,353 PointsWell 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:
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
3,483 PointsKevin Frostad
3,483 PointsI 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
15,353 PointsKevin Faust
15,353 PointsConstructors 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
3,483 PointsKevin Frostad
3,483 PointsI see, thanks for clearing that up.