【发布时间】:2015-04-02 17:31:00
【问题描述】:
在我的班级中,三个实例变量都是最终的。但是,当我尝试在 setter 方法中执行 this.inputsRelated = inputsRelated 之类的操作时,我收到一个可以理解的错误,提示无法分配 final 字段。但是 setter 方法中的方法/我应该如何处理方法 public void setInputsRelated(boolean inputsRelated) 和 public void setExpected(int expected) ?提前致谢!
public class ExceptionLogicParameters extends RuntimeException {
public final boolean inputsRelated;
public final int expected;
public final int found;
public ExceptionLogicParameters(boolean inputsRelated, int expected, int found)
{
this.inputsRelated = inputsRelated;
this.expected = expected;
this.found = found;
}
@Override
public String toString()
{
return "Get the the hell out of here!";
}
public boolean getInputsRelated()
{
return this.inputsRelated;
}
public int getExpected()
{
return this.expected;
}
public int getFound()
{
return this.found;
}
public void setInputsRelated(boolean inputsRelated)
{
this.inputsRelated = inputsRelated;
}
public void setExpected(int expected)
{
this.expected = expected;
}
}
【问题讨论】:
-
如果字段是最终的,则不应存在这些方法。 final 字段必须在声明或构造函数中设置。
-
如果要重新分配这些字段的值,为什么要使用 final?
-
已解决!教授犯了一个错误,将实例变量定为 final。
标签: java