I would like to ask why the following code causes error:
class A
{
A()
{
statObj.x = 5;
}
int x;
static A statObj = new A();
}
I get ExceptionInInitializerError. I don't understand why. In this case static variable statObj will be initialized as the first one. So, if I am right, static object statObj = new A() will be create as the first one.
What is the order of creation and initialization of this internal static object? Isn't statObj.x default initialized by 0 value, before the internal static object constructor is called statObj.A() ? If that ,why statObj.x behaves like it wasn't initialized (I fought it was default initialized by 0 value) ?
And one more why this problem only occurs in constructor and not in method ? The following code works fine:
class A
{
A()
{
}
void met1()
{
statObj.x = 5;
}
int x;
static A statObj = new A();
}
public MainClass
{
public static void main(String[] arg)
{
A a = new A();
a.statObj.met1();
}
}