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 (Retired) Meet Objects Constructors

Ishay Frenkel
Ishay Frenkel
1,620 Points

Challenge should work, but it shows "Bummer"

What's wrong with this answer?

GoKart.java
public class GoKart {
  private String mColor;

  public String getColor() {
    return mColor;
  }

  public void setColor(String color) {
    this.mColor = color; 
  }
}

1 Answer

Michael Hess
Michael Hess
24,512 Points

Hi Ishay,

Everything is looking good except it looks like there is not a constructor.

We want to add a constructor that excepts color as an argument. Then we want to set the member variable mColor equal to the color argument in the constructor.

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

The end result is:

public class GoKart {
  private String mColor = "red";

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

  public String getColor() {
    return mColor;
  }
}

If you have any other questions feel free to ask! Hope this helps!

Ishay Frenkel
Ishay Frenkel
1,620 Points

What's wrong with the setColor constructor?

Michael Hess
Michael Hess
24,512 Points

A class contains constructors that are invoked to create objects from the class blueprint. Constructor declarations look like method declarationsβ€”except that they use the name of the class and have no return type

This is what a constructor looks like -- notice how it doesn't have a return type? It's just the name of the class, GoKart, with the visibility modifier public in front.

public GoKart(){

  }

The setColor() method, in your code, is a void method. It's return type is void -- meaning that it does not return anything.

In summary a constructor:

  1. Has the same name as the class
  2. A constructor doesn't have a return type.

This is a link to Oracle's Java Tutorials explaining constructors : Providing Constructors for Your Classes

If there is anything else you would like me to explain -- I'll be happy to do so. Hope this helps!