3
public class Parent {
    public static int y=10 ;
}

public class Child extends Parent {
    static {
        y=20 ;
    }

    public static void main(String[] args) {
        System.out.println(Child.y);  // output = 20
    }
}

public class Test {
    public static void main(String[] args) {
        System.out.println(Child.y); // output = 10
    }
}

Note: in the first scenario, static block is getting executed. But this is not the same case in the second scenario. Why? Why does the output value differ? I am using jdk-17

KNU
  • 2,560
  • 5
  • 26
  • 39
  • Does this answer your question? [Static Initialization Blocks](https://stackoverflow.com/questions/2420389/static-initialization-blocks) – M. Yousfi May 09 '23 at 07:42
  • See the duplicate. Note the wording "A static field ***declared*** by `T`". What class your code uses doesn't matter. It is the class in which the field is *declared* that determines whether that class is initialised. – Sweeper May 09 '23 at 07:48
  • 3
    Java Language Specification [8.7. Static Initializers](https://docs.oracle.com/javase/specs/jls/se20/html/jls-8.html#jls-8.7): "A static initializer declared in a class is executed when the class is initialized" and [12.4.1. When Initialization Occurs](https://docs.oracle.com/javase/specs/jls/se20/html/jls-12.html#jls-12.4.1) "...instance of T is created ... static method declared by T is invoked ... static field declared by T is assigned ... static field declared by T is used..." (check the link for details) `Child` is not initialized since none of these four cases applies when running `Test` – user16320675 May 09 '23 at 07:54
  • Having said that, it is generally a bad idea to rely on static initialization order as it can hard to understand. – Stephen C May 09 '23 at 08:03
  • What happens in that static block in Child? The `y` there is actually the field of the class Parent, that is not a declaration of a new field of class Child... right? Yet we are allowed to reference Child.y field? I glanced over the Oracle docs now but didn't find something relevant – wi2ard May 09 '23 at 08:45
  • 1
    @GabiM check Java Language Specification [8.2. Class Members](https://docs.oracle.com/javase/specs/jls/se20/html/jls-8.html#jls-8.2) – user16320675 May 09 '23 at 09:13

0 Answers0