I am learning the static block functionality in core java.
public class ClassResolution {
static class Parent {
public static String name = "Sparsh";
static {
System.out.println("this is Parent");
name = "Parent";
}
}
static class Child extends Parent {
static {
System.out.println("this is Child");
name = "Child";
}
}
public static void main(String[] args) throws ClassNotFoundException {
System.out.println(Child.name);
}
}
I thought the output would be:
this is Parent
this is Child
Child
but the actual output is:
this is Parent
Parent
and I have no idea why.
Since name is a static field declared in Parent class, accessing it in the main method (even though it is accessed using the Child class name as a prefix) causes Parent class to be initialized. Child class is not initialized.
Therefore "this is Parent" is displayed (since the static initializer block of Parent is executed), "this is Child" is not displayed (since the static initializer block of Child is not executed) and the printed value of name is "Parent".
Here's the relevant JLS reference :
12.4. Initialization of Classes and Interfaces
Initialization of a class consists of executing its static initializers and the initializers for static fields (class variables) declared in the class.
Initialization of an interface consists of executing the initializers for fields (constants) declared in the interface.
12.4.1. When Initialization Occurs
A class or interface type T will be initialized immediately before the first occurrence of any one of the following:
T is a class and an instance of T is created.
A static method declared by T is invoked.
A static field declared by T is assigned.
A static field declared by T is used and the field is not a constant variable (§4.12.4).
T is a top level class (§7.6) and an assert statement (§14.10) lexically nested within T (§8.1.3) is executed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With