class Parent
{
static int y = 4;
}
class Child extends Parent
{
static
{
System.out.print("static Initialization block ");
y=9;
}
static void fun()
{
System.out.print(y);
}
}
public class Test
{
public static void main(String []args)
{
System.out.print(Child.y); // line L1
Child.fun(); // line L2
}
}
Line 1 outputs: 4
Line 2 Outputs: static Initialization block 9
Now, my Doubts are:
- I have read that whenever we initialize a class, static initialization block executed first then why line L1 not executing the static initialization block, while line L2 executes the static initialization block ?
- Does the static variable y of parent class inherited to child class or not?
Child.yis interpreted asParent.yin this case, becauseyis actually onParent. Decompile your class file withjavap -vto verify this. That's actually whyChild.yis an antipattern: you should always access static fields with the "correct" class.