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
Marcus Schumacher
16,616 PointsProblem with Java challenge
Here is the problem:
Add a public constructor to the GoKart.java class that allows the parameter color to be passed in. In the constructor store the argument color in the private color field.
My code:
public class GoKart {
private String mColor;
public colorSetter(String color) {
mColor = color;
}
public String getColor() {
return mColor;
}
}
I don't know why it works. And just another question. How long did it take you to get comfortable and understand the Java language? I still find it confusing after a few hours.
1 Answer
Alexander Bueno
5,398 PointsSo I am a little confused about your confusion, but hopefully I can address your problem. So first thing's first. A constructor is a special method that allows you to create an instance of your class (this is known as an object). With this constructor you can create as many instances of this class as you want and they will all have unique values to their member variables so long as you do not set the value of the member variable to static. Anyways the constructor method is special because of its ability to create an instance of its class as well as it being created by the method name being the exact same as the class name(also constructor methods do not return anything no need to use the reserved word void either).
I also noticed that your setter for mColor was a little odd. The name does not really matter too much however best practice is to have the method as "set" and then "VariableName" in this case it would be setColor() rather than colorSetter(). It's not to big of a deal, as it will not actually change your method runs, but a lot of coders will get on your case about it.
public class GoKart{
private String mColor;
// | | |
// v v v notice how the name of the constructor method is the exact same name of the class.
public GoKart(String color){
mColor = color;
}
}