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

Jason Scruggs
Jason Scruggs
567 Points

How to declare without initializing?

Is the field declaration in the question referring to class or the constructor? In either case, how do I declare it without initializing with "red"? Am I to simply leave that space after the equals sign blank? I tried a combination of methods but to no avail. Please assist.

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

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

  public String getColor() {
    return color;
  }

}

2 Answers

Jonathan Grieve
MOD
Jonathan Grieve
Treehouse Moderator 91,252 Points

As you may know, initialising a variable means giving a variable a value. At the moment your code is declaring the variable color and then overriding it in your constructor.

Try typing private String color in the global scope of the GoKart class which will declare the variable but not initialise it at that point.

Jason Scruggs
Jason Scruggs
567 Points

Thanks for that prompt reply! I tried to do as you advised but I'm still getting a message that reads: "Whoops, color is still being assigned in the field declaration". Here's my updated code:

class GoKart { private String color;

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

public String getColor() { return color; }

}

Jonathan Grieve
Jonathan Grieve
Treehouse Moderator 91,252 Points

There's one more thing I should have directed you to do. Sorry :)

In your constructor in task 2 you need to tell the constructor to set the value of this.color to the the value of your color variable, rather than hard coding the value red in the constructor. Basically, by the time the code challenge ends you won't have any reference to the colour red at all because later on you'll pass a value in when you instantiate your object.

Hope this all makes sense :)

Jason Scruggs
Jason Scruggs
567 Points

It's slowly (very slowly) starting to make sense :) I managed to get pass the code challenge. Thanks again for your help!