Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't the static block of Child class executed when Child.name is accessed? [duplicate]

Tags:

java

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.

like image 832
sparsh610 Avatar asked May 19 '16 05:05

sparsh610


1 Answers

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.

like image 119
Eran Avatar answered Sep 20 '22 15:09

Eran