我可以使用静态块中的字段并将其分配给类字段吗?

时间:2019-02-12 13:33:30

标签: java static-block

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

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字段。

1 个答案:

答案 0 :(得分:1)

  

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

否,因为您没有在静态初始值设定项中声明字段:这些字段是局部变量。只能在该块中访问它们。

如果您想要一个字段,请声明为:

static int initNr = 200;

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

现在您可以在课程的其余部分中参考initNr