0
class Super { static String ID = "SUPER_ID"; }

class SubClass extends Super{
  static { System.out.print("In SubClass"); }
}

class Test{
  public static void main(String[] args) {
    System.out.println(SubClass.ID);
  }
}

Why i have in output

SUPER_ID

instead of

In SubClass
SUPER_ID


SubClass will be loaded in the first call of object. So why static init block doesn't execute? Thanks.

2
  • You are not initializing SubClass, you are referring to the static field in it (it extends Super). Commented Mar 5, 2014 at 8:02
  • @MarounMaroun but if i have interface which contains static constants my interface load into JVM in the first time i called. What the difference? Commented Mar 5, 2014 at 8:06

3 Answers 3

1

Because during compile time itself, SubClass.ID will be changed to Super.ID by the compiler. And like @Kugathasan Abimaran says, inheritance and static are two different things.

Example :

public class SampleClass {
    public static void main(String[] args) {
        System.out.println(SubClass.ID);
        System.out.println(SubClass.i);
    }
}

class Super {
    static String ID = "SUPER_ID";
}

class SubClass extends Super {
    static {
        System.out.println("In SubClass");
    }

    static int i;
}

Output :
SUPER_ID
In SubClass // only when accessing a variable of subclass, the class will be initialized.
0
Sign up to request clarification or add additional context in comments.

3 Comments

inheritance with static members? Wrong wordings.
@KugathasanAbimaran - What I meant to say was - The class is not yet loaded into the JVM and during compilation itself, SubClass.ID will be referenced as Super.ID
I think a more appropriate term will be 'static fields linking', it is done at compile time.
0

Your class is not loaded by class loader because it was not used in your Test class, If you want to load it just add the statement Class.forName("SubClass"); in your test class after that your could be able to see the result as you are expecting. you can also load this class using class loader instead of Class.forName.

class Test{
    public static void main(String[] args) {
    Class.forName("SubClass");
    //Thread.currentThread().getContextClassLoader().loadClass("SubClass");
    System.out.println(SubClass.ID);
    }
}

Comments

0

According to The Java Language Specification:

A reference to a static field 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.

More info

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.