Sergey Shustikov
Sergey Shustikov

Reputation: 15821

Why static block doesn't load in called object?

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.

Upvotes: 0

Views: 112

Answers (3)

Eugene Evdokimov
Eugene Evdokimov

Reputation: 2545

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

Upvotes: 0

Naveen Ramawat
Naveen Ramawat

Reputation: 1445

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);
    }
}

Upvotes: 0

TheLostMind
TheLostMind

Reputation: 36304

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

Upvotes: 1

Related Questions