I am working on an assignment and I'm stuck on this error: cannot assign a value to final variable count
Here is my code so far...
public class List
{
private final int Max = 25;
private final int count;
private Person list[];
public List()
{
count = 0;
list = new Person[Max];
}
public void addSomeone(Person p)
{
if (count < Max){
count++; // THIS IS WHERE THE ERROR OCCURS
list[count-1] = p;
}
}
public String toString()
{
String report = "";
for (int x=0; x < count; x++)
report += list[x].toString() + "\n";
return report;
}
}
I'm very new to java and am obviously not a computer whiz so please explain the problem/solution in the simplest terms possible. Thank you so much.
It is throwing error because you have declared count as a final variable. Final variables are nothing but constants. We cannot change the value of a final variable once it is initialized.
'final' keyword works as constant. You can assign a value then and there at the declartion or you can assign a value in a constructor but that too only once. You cannot inc-dec its value further down the code. Therefore count++ will generate an error.
Also know that 'final' when used with classes or functions, prevents them from being inherited into the sub class.
When you declare a variable
final
you basically tell the compiler that this variable is constant and will NOT change. You declaredcount
final, but you hadn't initialized (set a value) it yet. That's why you were allowed to set it's value in your constructorpublic List() {}
: final variables can be initialized once, and after that, they can't be modified.There are exceptions to this though, if you'd for example created an object with an int value of count, and added a setter, you'd still be able to modify the final object.
Example of that:
count++;
will throw an error. Per Oracle,You can follow along with that article here. Looking at your code, it seems that you really don't want
count
to be final. You want to be able to change its value throughout the program. The fix would be to remove thefinal
modifier.