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

Jackie Wang
Jackie Wang
479 Points

Now in the body of your constructor, set the private field color to the value of the color argument passed into the cons

help me !!!

GoKart.java
class GoKart {
  private String color = "red";

  public GoKart(String color) {
    color = color;

  }
  public String getColor() {
    return color;
  }

}

1 Answer

andren
andren
28,558 Points

When you have a field variable and a parameter that share the same name you have to prepend the field variable with the this keyword in order help java distinguish between the two variables. Like this:

class GoKart {
  private String color = "red";

  public GoKart(String color) {
    this.color = color;

  }
  public String getColor() {
    return color;
  }
}

That will allow you to pass to task 3.

Jackie Wang
Jackie Wang
479 Points

I forgot to return color at first and thank you so much

Jackie Wang
Jackie Wang
479 Points

class GoKart { private String mcolor = "red";

public GoKart(String color) { mcolor = color;

} public String getColor() { return mcolor; }

} why this one can't pass

andren
andren
28,558 Points

That code is valid (it will compile and work) but it modifies code the challenge did not ask you to modify. Challenges tend to be pretty picky about you changing code that was already in place, and changing names is almost always something that will lead the challenge to fail, even if the code you end up writing actually would work fine.