【问题标题】:Can I use a field from a static block and assign it to the class field?我可以使用静态块中的字段并将其分配给类字段吗?
【发布时间】:2019-02-12 13:33:30
【问题描述】:

我想根据位置对比赛进行编号,并且应该在构造函数中创建汽车时完成。问题是我可以从静态块中获取一个字段并将其值分配给车辆类字段吗?

public class Vehicle {

    static {
        Locale[] loc = {Locale.US, Locale.JAPAN, Locale.ITALIAN,};
        int[] beginNr = {100, 1000, 10000};
        int initNr = 200;
        Locale defLoc = Locale.getDefault();

        for (int i=0; i<loc.length; i++)
            if (defLoc.equals(loc[i])){
                initNr  = beginNr[i];
                break;
            }
    }

    private int width, height, lenght, weight;
    private Person owner;
    private VehicleStatus status;
    private static int count;
    private int currentNumber;


    public Vehicle(Person owner, int width, int height, int lenght, int weight) {
        this.width = width;
        this.height = height;
        this.lenght = lenght;
        this.weight = weight;
        this.owner = owner;
        status = STOPPED;
        currentNumber = ++count;
    }

我希望将initNr 字段的值分配给currentNumber 字段。

【问题讨论】:

  • 您对如何根据位置创建汽车自动编号有什么建议吗?
  • 您可以简单地引用静态块中的字段currentNumber,而不是initNr

标签: java static-block


【解决方案1】:

问题是我可以从静态块中获取一个字段并将其值分配给车辆类字段吗?

不,因为您没有在静态初始化程序中声明字段:这些是局部变量。它们只能在该块内访问。

如果你想要一个字段,那么声明它:

static int initNr = 200;

static {
  // Stuff where you change the value of initNr.
}

现在你可以在其余的课程中参考initNr

【讨论】:

    猜你喜欢
    • 2011-07-12
    • 2010-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-04
    相关资源
    最近更新 更多