Recently, my friend Chandru came up with a new problem in java.
Try solving the below problem without java.exe
public class StaticUnderstanding {
public static void main(String[] args) {
SubClass.dummyMethod();
}
}
class SuperClass {
static {
System.out.println("In superclass...");
}
protected static void dummyMethod(){
System.out.println("In dummy method...");
}
}
class SubClass extends SuperClass {
static {
System.out.println("In subclass...");
}
}
If you come with any answer other than the below, then you need to read JLS 12.4 – Initialization of Classes and Interfaces.
In superclass…
In dummy method…
Thanks to Sai for getting this awesome data !!
Advertisement











Only see one option – changing SubClass:
class SubClass extends SuperClass {
static {
System.out.println(“In subclass…”);
}
protected static void dummyMethod() {
SuperClass.dummyMethod();
}
}
Otherwise, it’s the appropriate behaviour, since the method is static, there’s no need for calling the most specific class’s static block.
You see the difference by calling new SubClass().dummyMethod();