Assign a static variable before declaration

I am learning Java and writing simple code below:

public class Test { private int a = b; private final static int b = 10; public int getA() { return a; } } public class Hello { public static void main(String[] args) { Test test = new Test(); System.out.println(test.getA()); } } 

Result: 10 . Well done! It works successfully and has no error.

Can someone explain why I can assign a static variable before declaring it?

+5
source share
5 answers

Appointment

 private int a = b; 

happens when a new instance of Test (just before the constructor is called).

Declaring and initializing the static variable b is done before the instance is created when the class is loaded.

The order of the instructions does not matter, since static variables are always initialized first.

+5
source

Javavariables are initialized in the following order:

  • Static variables of superclasses, if any
  • static variables of the current class.
  • Static variables and static blocks in the order in which they are declared
  • Superclass Instance Variables
  • All instance variables of the current class.
  • Instance variables and instance-level initialization blocks in declaration order

Therefore, "b" is initialized before "a".

Hope this helps.

+1
source

The order of declaration of variables in your code does not matter much, since in reality a static variable will be initialized to non-static.

0
source

Static variables are tied to a class, which, of course, always exists before class instances. This way you can freely assign it to instance fields.

0
source

The code you wrote works well because private final static int b = 10; is a class variable (static field). These types of variables are initialized for the first.

Then the line private int a = b; which initialize the instance variable (field) a .

In short, the order in which these variables are declared in your code does not matter. Class variables are always declared before instance variables.

0
source

Source: https://habr.com/ru/post/1210095/


All Articles