Why is the static block of the Child class not executed when accessing Child.name?

I am studying the static block function in the Java kernel.

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 conclusion is:

 this is Parent Parent 

and I have no idea why.

+8
java
source share
1 answer

Since name is a static field declared in the Parent class, access to it in the main method (even if it is available using the name of the Child class as a prefix), the Parent class is initialized. Child class is not initialized.

Therefore, "this is Parent" displayed (since the "this is Parent" static initializer block is running), "this is Child" is not displayed (since the static Child initializer block is not ), but the printed name is "Parent" .

Here's the relevant JLS link:

12.4. Initialization of classes and interfaces

Initializing a class consists of executing its static initializers and initializers for static fields (class variables) declared in the class.

Initialization of the interface consists in executing initializers for the 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 of the following:

  • T is a class and an instance of T. is created.

  • The static method declared by T. is called.

  • Assigned to a static field declared by T.

  • 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 the statement (ยง14.10) holds, lexically embedded in T (ยง8.1.3).

+14
source share

All Articles