Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Java Java Objects (Retired) Harnessing the Power of Objects Methods and Constants

William Forbes
William Forbes
21,469 Points

Initialization to zero

Hello, For the attached code the prompt was to "add a private uninitialized field to the constructor, then initialize it to zero". For the field mBarsCount shown in the code would:

" private int mBarsCount; " be the same thing as " private int mBarsCount = 0; "

I thought an unitialized int would just be expressed as "private int mBarsCount; " In other words was the wording just confusing and could it have just said "add a private field and initialize it to zero", or is there a functional difference between intializing to zero vs not initializing the field?

THanks!!

1 Answer

I think you are missing the constructor part.

public class GoKart {
  public static final int MAX_BARS = 8;
  private int mBarsCount; // declares the field

  private String mColor;

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

  public String getColor() {
    return mColor;
  }

  public void getBarsCount() {
    mBarsCount = 0; // initializes the field
  }
}