I have a class
public class MyMain{
public static void main(String... arg){
Temp t = new Temp(){
{
System.out.println(" instance initialize");
}
};
}
}
class Temp{
int i;
{
i=9;
System.out.println("Static"+i);
}
Temp(){
System.out.println("Temp const "+i);
}
}
When i execute the main method the output comes:
Static9
Temp const 9
instance initialize
Ideally, the blocks are executed before the constructor, but the inline initialization block is called after the Constructor. Why?
You’re creating a subclass of
Temp. For each class, any instance initializers are executed before the constructor body – but the superclass goes through initialization before the subclass initialization. So the execution flow is:ObjectObjectTempTempI would strongly advise you to refactor any code which looked like this anyway – aim for clarity rather than cleverness.