gpt4 book ai didi

java - 不可变类中的编译时错误 : (final) variable might not have been initialized

转载 作者:行者123 更新时间:2023-12-01 08:09:18 25 4
gpt4 key购买 nike

代码尽可能简单,但我似乎遇到了编译器错误。我错过了什么?

顺便说一句,完全删除 _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; }
}

最佳答案

您必须初始化最终字段,但您只是在构造函数中初始化了局部变量。

改变

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;

关于java - 不可变类中的编译时错误 : (final) variable might not have been initialized,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18824287/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com