Reputation: 507
we know that a static block in java is resovled while compliling, not at runtime. Hence again We know that a static inner class is instantiated during the first call to the nested class. Now suppose the nested class is having a static block. So, in that case can we say that static block inside the nested class will be resolved when the first attempt to access that nested class is made? Sample code:
public class A
{
public static class B
{
static A a;
static
{
a=new A();
}
public static A getA()
{
return a;
}
}
}
Now I am accessing as: A a= A.b.getInstance(); I hope at that point only static block in B will be executed and not before that.
Upvotes: 0
Views: 1378
Reputation: 11487
From jls Compile
time error will happen from static blocks
only when
If a static initializer cannot complete normally.
If a return statement appears anywhere within a static initializer.
If the keyword this or the keyword super or any type variable declared outside the static initializer, appears anywhere within a static initializer.
static block
will be executed when the class is initialized
, so in your example, the static block
inside your static class B
will get executed first.
Upvotes: 0
Reputation: 48817
This should answer your question:
public class Test {
public Test() {
System.out.println("Test instantiated");
}
public static class Inner {
static {
System.out.println("Static block executed");
}
public Inner() {
System.out.println("Test.Inner instantiated");
}
}
}
When calling:
Test test = new Test();
Test.Inner inner = new Test.Inner();
We get:
Test instantiated
Static block executed
Test.Inner instantiated
Upvotes: 4
Reputation: 47290
static block in java is resovled while compliling
No it isn't.
All static code is resolved once by the classloader, when loaded/initalized.
Upvotes: 1