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 trialRodrigo Alarcon
8,028 PointsJava Objects
Please help me. The challenge is...
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.
I am not sure of what i need to write, but the code here is not what I wrote but what was already there
public class GoKart {
private String mColor = "red";
public String getColor() {
return mColor;
}
}
2 Answers
Steve Hunter
57,712 PointsHi Rodrigo,
A constructor is a method inside the class that takes the name of the class. You can define the parameters that it accepts when you write the code - in this case, it wants to receive the 'color' (a string) so it can create the instance of GoKart. A constructor is public (generally!) and returns nothing (except a newly created instance which isn't expressly written) and accepts whatever parameters that make sense. In this case, it wants a string. That string is then assigned to the mColor
member variable inside the new instance of that GoKart - this means we need to remove the assignment of "red" to the member variable - we can now assign anything we choose in there.
This all looks like:
public class GoKart {
private String mColor; // remove the assignment here
public String getColor() {
return mColor;
}
// OUR CODE HERE
public GoKart(String color){ // passes in a string called color inside the method
mColor = color; // assign color to mColor for the instance of GoKart
}
}
I hope that helps.
Steve.
Rodrigo Alarcon
8,028 PointsThanks a lot
Steve Hunter
57,712 PointsHey, no problem!
Rodrigo Alarcon
8,028 PointsRodrigo Alarcon
8,028 PointsPlease help me with my other question. https://teamtreehouse.com/community/java-object-again