0

I want to number the races depending on their location and it should be done when creating the car in the constructor. The question is can I get a field from a static block and assign its value to the vehicle class field?

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;
    }

I want the value of the initNr field to be assigned to the currentNumber field.

khelwood
  • 55,782
  • 14
  • 81
  • 108

1 Answers1

1

The question is can I get a field from a static block and assign its value to the vehicle class field?

No, because you don't declare fields in a static initializer: those are local variables. They can only be accessed within that block.

If you want a field, declare it so:

static int initNr = 200;

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

Now you can refer to initNr in the rest of the class.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243