代码尽可能简单,但我似乎遇到了编译器错误。我错过了什么?
作为旁注,完全删除_name
字段只会在下一个字段中生成相同的错误。
P.S。:在这一个上期待相当多的减票,感觉我错过了一些非常简单的东西。
package mkumpan.helpers;
public final class BotState
{
private final String _name;
private final double _x;
private final double _y;
private final double _energy;
private final double _heading;
private final double _velocity;
public BotState(
String name,
double x,
double y,
double energy,
double heading,
double velocity
) {
String _name = name;
double _x = x;
double _y = y;
double _energy = energy;
double _heading = heading;
double _velocity = velocity;
} // BotState.java:26: error: variable _name might not have been initialized
public String getName() { return _name; }
public double getX() { return _x; }
public double getY() { return _y; }
public double getEnergy() { return _energy; }
public double getHeading() { return _heading; }
public double getVelocity() { return _velocity; }
}
答案 0 :(得分:6)
您必须初始化最终字段,但您只是在构造函数中初始化了局部变量。
更改
String _name = name;
double _x = x;
double _y = y;
double _energy = energy;
double _heading = heading;
double _velocity = velocity;
到
this._name = name;
this._x = x;
this._y = y;
this._energy = energy;
this._heading = heading;
this._velocity = velocity;
答案 1 :(得分:0)
无需在{}。
之间的构造函数体内再次添加类似“double”的变量类型