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) Harnessing the Power of Objects Methods and Constants

Now let's add a private uninitialized field to store the currrent number of energy bars. Name it mBarsCount. Initialize

Now let's add a private uninitialized field to store the currrent number of energy bars. Name it mBarsCount. Initialize it to zero in the constructor

I know the answer to this question but it say initialize it to zero in the constructor, so it shouldn't be like the way I coded at the bottom explain me why I am wrong and explain me the concept or point to use constructors please

GoKart.java
public class GoKart {
  public static final int MAX_ENERGY = 8;
  private String mColor;

  private mBarsCount;

  public GoKart(int barsCount)
  {
    mBarsCount = barsCount;
  }

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

  public String getColor() {
    return mColor;
  } 
}

1 Answer

Hi there,

First, you need to create the private, uninitialized member variable named mBarsCount. It is going to hold a number; an integer:

  private int mBarsCount;

Then, the question asks you to initialize it to 0 inside the constructor - that looks like:

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

A constructor is used to create an instance of a class. It is a method inside of the class that will be called every time an instance is created. At the point of creation, member variables can be set by either using a parameter passed into the constructor, such as the color of the Kart, or they can be set to their starting state, like mBarsCount. Every new Kart has zero energy bars.

Yes, it would be possible to redefine the constructor to be able to create an instance with a color and a number of bars, but that's not the challenge here - every Kart starts life with no energy bars.

So the constructor for this class creates a new Kart of a specified color and kindly empties its fuel tank. ;-)

Shout if you need more.

Steve.