Value of static variable not changed even after initializing the child class in java?

  • A+
Category:Languages

When I invoked the static variable y by using subclass.y the static block is not executed and the value of y didn't get updated.

class Par {     static int y = 4; }  class Checks extends Par {     static {         y = 5;     } }  public class Check {     public static void main(String args[]) {         System.out.println(checks.y);// here printing 4     } } 

As static is shared among all subclasses the value is supposed to be updated.

What could be the reason behind it?

 


The field y is not declared by class checks.

Even if it's accessed with checks.y, the runtime will initialize the class that declares the referenced value.

In other words, the class checks is in a sense not used at runtime.

This is an example of the wrong of accessing static members through subclasses, for which you get a compile-time warning.


There's a simple explanation in the specification:

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.
    ...
    A reference to a static field (§8.3.1.1) causes initialization of only the class or interface that actually declares it, even though it might be referred to through the name of a subclass, a subinterface, or a class that implements an interface.

The last note explains why your subclass is not being initialized.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: