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 Meet Objects Add a Constructor

Borislav Milev
Borislav Milev
1,218 Points

I don't understand where is my mistake

Can someone tell me where I go wrong. Thank you

GoKart.java
class GoKart {
  private String kartColor;

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

  public String getKartColor() {
    return kartColor;
  }


}

1 Answer

andren
andren
28,538 Points

The problem is that you have changed the name of the color field variable, which the task never asked you to do. Changing or adding anything the task does not explicitly ask for will often result in your code being marked as incorrect even if it technically works.

To complete this task you have to leave the color field variable name intact. In order to set the color field variable equal to the color parameter in the constructor you have to use the "this" prefix for the field variable. That makes it clear to Java which of the color variables you are referring to. Like this:

class GoKart {
  private String color = "red";

  public String getColor() {
    return color;
  }

   public GoKart(String color) {
     this.color = color; // "this.color" is the color field variable, "color" is the parameter.
  }
}

That code will allow you to pass onto task 3.