Reputation: 768
I have two top-level classes(BaseClass and B), BaseClass has main method in it and also has inner class(named Laptop). I know that static block is executed whenever class is loaded but for the following code:
package kkk;
public class BaseClass
{
static BaseClass e=new BaseClass();
public BaseClass()
{
System.out.println("In baseclass constructor");
}
{
System.out.println("in baseclass nonstatic block");
}
static
{
System.out.println("in baseclass static block");
}
protected static class Laptop
{
int x=8;
public Laptop()
{
System.out.println("Inside laptop class");
}
void m1()
{
System.out.println("Inside inner class method");
}
}
public void hem()
{
System.out.println("In base class hem");
}
public static void main(String args[])
{
e.hem();
System.out.println("In main method baseclass");
B h=new B();
h.bhel();
}
}
class B
{
void bhel()
{
BaseClass.Laptop obj=new BaseClass.Laptop();
System.out.println(obj.x);
obj.m1();
}
}
By running above code, i am getting output as:
in baseclass nonstatic block
In baseclass constructor
in baseclass static block
In base class hem
In main method baseclass
Inside laptop class
8
Inside inner class
e is static reference variable and memory must be allotted to it. So, static block is executed. But, why non-static block is executed before static block??
Upvotes: 2
Views: 764
Reputation: 394146
All static variable declarations and static initialization blocks are evaluated/executed in the order they appear in the source code when the class is initialized.
static BaseClass e=new BaseClass();
this creates an instance of BaseClass
when the class is initialized and causes the instance initialization block to be called before the constructor is executed.
Since this line appears before the static initialization block, it is executed before that block, which means the instance initialization block is called before the static initialization block.
Upvotes: 7