0
Why does the part between line 2 to 4 executes first when we know that Constructor gets invoked first always ?
When I remove the curly braces from print statement between line 2 and 4, the code produces error. I know that print statement cannot be used inside class. But I wasn't able to figure out why it works when print statement is surrounded by curly braces inside a class. A detailed explanation or a reference to the answer of the problem would be amazing :) https://www.sololearn.com/post/1690816/?ref=app
1 Antwort
+ 3
Because it is wrong that the constructor comes first.
In your case:
{
System.out.println("Instance Init");
}
This block is called an instance block. It gets executed when you create an instance of your class. And it is executed before constructor.
static{
}
This one is a static block. It gets executed when the class is loaded and before instance block+constructor.
I hope this code helps you:
https://code.sololearn.com/cRKxAwr2rE6t/?ref=app
Inside the comments there are some resources.