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

Petko Delchev
Petko Delchev
7,414 Points

Cannot assign value to final?!

Error:

"./GoKart.java:13: error: cannot assign a value to final variable mBars mBars = MAX_BARS; ^ 1 error"

What is wrong.. Is mBars final or not?! I try without final and had error again..

Thank you

GoKart.java
public class GoKart {

  public static final int MAX_BARS = 8;
  private String mColor;
  public final int mBars;

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

  public void battery() {
  mBars = MAX_BARS;
  }

  public String getColor() {
    return mColor;
  } 
}

1 Answer

Hi Petko,

The way it is written now "public final int mBars;" mBars is indeed a final variable which is why it is not allowing you to reassign it in your constructor and battery methods. Also if you are declaring a variable as final you must give it a value. ex: "public final int mBars=4;" Additionally, I would recommend making all of your instance variable private instead of public. Because of their scope they already can be used by any method with in the class, but would not be susceptible to being altered by another class.

Cheers, Connor

Petko Delchev
Petko Delchev
7,414 Points

Thank you Connor,

I was trying to finish the entire challange on the first step... How stupid am I!! :)