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

I'm having trouble with constuctors

i dont remember him talking about adding colors so i am a little lost

GoKart.java
public class GoKart {
  private String mColor = "red";
  public   
  public String getColor() {
    return mColor;
  }
}

1 Answer

Christopher Augg
Christopher Augg
21,223 Points

Hello Mike,

Constructors are used to create an instance of a class that we write. We also call these instances objects. For example, if I wrote a class for a car, I could instantiate or create many different cars from that one class.

      Car carOne = new Car();
      Car carTwo = new Car();

Notice here that I have called the Car() constructor and I pass no arguments at all. We can do this because Java classes all have a default constructor for when we do not write one in our class. But what if I want to make a car blue when I create it?

       Car carThree = new Car(blue);

In order to do this we need to write a Constructor in the class and pass it an argument. We should make sure the name of the constructor matches the name of the class.

       public Car( String color) {
           mColor = color;   // mColor is a private member variable that holds a String to represent the color of this car. 
       }

The instructions for this challenge:

"Add a public constructor to the GoKart.java class that allows the parameter color to be passed in. In the constructor store the argument color in the private color field."

I think you can get this now. Let me know if you are still stuck.

Regards,

Chris