We have an outer class with name FooClass and a UsedClass inside of FooClass as field.
In addition, we have normal 2 block and static two block. We initialize usedClass field while field definition. When we call FooClass constructor, what is running priority. All classes and output are below.
The output is:
static block before
static block after
normal block before
UsedClass constructor
normal block after
FooClass constructor
UsedClass doSth method
In addition, we have normal 2 block and static two block. We initialize usedClass field while field definition. When we call FooClass constructor, what is running priority. All classes and output are below.
public class FooClass { public FooClass() { System.out.println("FooClass constructor"); } { System.out.println("normal block before"); } static { System.out.println("static block before"); } public UsedClass innerClass = new UsedClass(); { System.out.println("normal block after"); } static { System.out.println("static block after"); } public void doSth(){ innerClass.doSth(); } }
public class UsedClass{ public UsedClass() { System.out.println("UsedClass constructor"); } public void doSth() { System.out.println("UsedClass doSth method"); } }
public class Main { public static void main(String[] args) { FooClass foo = new FooClass(); foo.doSth(); } }
The output is:
static block before
static block after
normal block before
UsedClass constructor
normal block after
FooClass constructor
UsedClass doSth method