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

Jennifer Kartchner
Jennifer Kartchner
1,844 Points

cannot assign a value to final variable mBarCount

cannot assign a value to final variable mBarCount

GoKart.java
public class GoKart {
  private String mColor;

  public static final int mBarCount = 8;

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

  public String getColor() {
    return mColor;
  } 
}

1 Answer

Aaron Graham
Aaron Graham
18,033 Points

The keyword 'final' makes mBarCount a constant. Not being able to assign a value to it is exactly what it should do.

Edit: To give a little more explanation, if mBarCount is meant to be a constant number in your code (given your code, I don't think that is the case), leave 'final' in there, and to follow good coding practices, change the name to something like M_BAR_COUNT, since it is a constant. Also, you need to remove the reassignment of mBarCount to '0'. You can't reassign a constant. The compiler will catch it every time.

The way I think your code should work (if I remember this code challenge correctly), is that you should have a constant defined that stores the maximum number of bars and a member variable that stores the current number of bars;

public static final int MAX_BARS = 8;
public static int mBarCount;

mBarCount just stores the current number of bars. Then, when the kart is recharged, you can simply do:

mBarCount = MAX_BARS;

Using constants is to prevent you from accidentally doing something like:

MAX_BARS = mBarCount;

With MAX_BARS defined as 'final', the compiler will catch it. If it weren't defined with 'final' you would have just built a bug.

Hope that helps.