Value of static variable not changed even after initializing the child class in Java [duplicate]

The field y is not declared by class Checks.

Reading static fields doesn’t trigger initialization of the referenced class (Checks), unless that class is the one in which the field is declared (see JLS quote below). In this example, even if y is accessed through Checks, that will only trigger the initialization of Par because Par is the class declaring y.

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

This is perhaps one illustration of why it’s wrong to access static members through subclasses, something that causes 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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)