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

Schwartz Prince
PLUS
Schwartz Prince
Courses Plus Student 2,132 Points

Please help me in finding out the error

I couldn't get output for this piece of code. Can someone please help me.

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

  public Gokart(String color)
    {
      private color = color;
    }
  public String getColor() {
    return color;
  }


}

1 Answer

Hi there,

You have the bsic of the constructor correct; it is public, returns nothing, takes a String parameter and is named the same as the class. Inside the constructor, you want to set the color variable that already exists within the class. You want to set that to the value that you have passed into the constructor.

Use this to identify that you're setting a variable belonging to the class and assign the passed-in parameter to it.

Something like:

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

Here, the first use of color refers to the private member variable inside the class. The second color is the one you created within the constructor. You could call that anything you like, if that's clearer:

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

I hope that helps.

Steve.