Kat*_*ryn 8 java variables variable-assignment
我正在进行一项任务,我遇到了这个错误:无法为最终变量计数赋值
这是我到目前为止的代码......
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;
}
}
Run Code Online (Sandbox Code Playgroud)
我对java很新,显然不是计算机专家,所以请用最简单的术语解释问题/解决方案.非常感谢.
当你声明一个变量时,final你基本上是告诉编译器这个变量是常量并且不会改变。您声明了countfinal,但您还没有对其进行初始化(设置值)。这就是为什么允许您在构造函数中设置它的值的原因public List() {}:final 变量可以初始化一次,之后就不能修改了。
不过也有例外,例如,如果您创建了一个 int 值为 count 的对象,并添加了一个 setter,您仍然可以修改最终对象。
例如:
public class ExampleObject {
private int count;
public ExampleObject(int count) {
this.count = count;
}
public void setCount(int count) {
this.count = count;
}
public int getCount() {
return count;
}
}
public class ExampleDemo {
private static final ExampleObject obj = new ExampleObject(25);
public static void main(String[] args) {
obj = new ExampleObject(100); //not allowed: cannot assign a value to final variable
obj.setCount(100); //allowed
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
36784 次 |
| 最近记录: |