有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

不可变类:(final)变量中的java Compiletime错误可能尚未初始化

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

作为旁注,完全删除_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; }
}

共 (2) 个答案

  1. # 1 楼答案

    无需在{}之间的构造函数体中再次放置变量类型,如“double”

  2. # 2 楼答案

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

    改变

    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;