Within the class, the order in which the variables are defined determines the order of initialization, and the immediate variable definitions are scattered outside the method definition, and they are still initialized before any method (including the constructor) is called.
The order in which initialization is static, followed by non-static objects
For example:
Class cat{ Private Dog Dog1=new dog (1); Static Private Dog Dog2=new dog (2); public cat (int n) { System.out.println ("+n+", "Cat Only");} } Class dog{public Dog (int n) { System.out.println ("Dog (" +n+ ")");} } public class Teststatic {public static void Main (string[] args) { System.out.println ("Test ..."); Cat cat=new Cat (1);} }
Operation Result:
Test ... Dog (2) Dog (1) 1th cat
The Cat class and the Dog class constructor print information in order to see the initialization information
In the main method, a cat class was created, with the exception of the construction method, there are two objects, one is static dog and the other is dog, because the static object is initialized first, so the Dog (2) is printed first, then the Dog (1)
Finally, we call cat's construction method, print out cat (1)
Non-static instance initialization
The contents of the initialization in {} are executed before the constructor, and each generation of the class {} will be re-initialized
Questions about initialization in Java