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 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,558 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.