It is my understanding that every time a class instance is created the instance init block runs. When I tried to test this, the instance init block ran for the first two created instances, but not the third.
Here’s the code:
class ModuleInit {
ModuleInit (int x) { System.out.println("1-arg const"); }
ModuleInit () { System.out.println("No-arg const"); }
static { System.out.println("First static init"); }
{ System.out.println("1st instance init"); }
{ System.out.println("2nd instance init"); }
static { System.out.println("2nd static init"); }
public static void main(String[] args)
{
new ModuleInit();
new ModuleInit(8);
}
}
and here’s the output:
First static init
2nd static init
1st instance init
2nd instance init
No-arg const
1st instance init
2nd instance init
1-arg const
<---Missing instance init for ModuleInt(int x)?
I thought that when the new class instance with the int arg was created ( ModuleInit(8) ) that there should be another instance init block run. Can someone explain why this doesn’t happen here?
The instance initialization blocks run as the first line within the constructors (that is, after the call to
super()orthis(), whether implicit or declared), so they are running before the constructor prints out its line:This code would be equivalent: