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

I'm stuck!

I cant understand the question.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.

GoKart.java
public class GoKart {
  private String mColor = "red";

  public String getColor() {
    return mColor;
  }
}

2 Answers

Geovanie Alvarez
Geovanie Alvarez
21,500 Points
public class GoKart {
  private String mColor = "red";

  public GoKart(String color){ // <----- public constructor and parameter
    mColor = color; // <----- assign the mColor variable to the parameter variable
  }

  public String getColor() {
    return mColor;
  }
}
Grigorij Schleifer
Grigorij Schleifer
10,365 Points

Hi Venzislav,

a constructor is helping you to create objects of a class (here GoKart) and add parameters to them (here color).

To create a new object of the GoKart class you would write (not needed for the challenge):

GoKart gk = new GoKart(red)

On the right side of the line you are writing "new GoKart(red)" and this calls the constructor that accepts a String "red" as color for your GoKart. So gk is the object of the GoKart class that has the color "red".

To ensure that the constructor works properly you must follow some naming conventions. The name of the constructor must be the same as the class. Constructors return nothing and take different arguments (in this challenge a String representation of the color).

To create a constructor your code could look like this:

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

Hope that helps :)

Grigorij