4

I stumbled upon following code

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

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

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

We are referencing class Sub as Sub.id. So i expected the static block in the Sub class to be executed and "In Sub" to be printed but to my surprise it does not. Although variable ID is visible to Sub class from Super class since we are referring to the variable using Sub class I expect it to be loaded first. And if it gets loaded then the static block should get executed.

Since it is not getting printed is it that Sub class is not loaded at all? How is that possible when I am clearly referencing it in my code. I mean how a class could be recognized without getting loaded into the memory? Something I am missing?

John Farrelly
  • 7,289
  • 9
  • 42
  • 52
Aniket Thakur
  • 66,731
  • 38
  • 279
  • 289
  • Static variables aren't inherited. Interestingly enough, Eclipse replaces `Sub` with `Super` for me. So I'd suspect there's some compile-time things going on. – awksp Jun 11 '14 at 19:07
  • Variables are never inherited be it static or instance. They are shadowed but that's not the point here. – Aniket Thakur Jun 11 '14 at 19:10
  • Oh fine. Static *fields* aren't inherited then. You aren't calling `Sub.ID`. You're calling `Super.ID`. – awksp Jun 11 '14 at 19:10
  • You are correct, ID is in super class, remember class loading/initiation hierarchy. ID found in super class, so done there. Just to prove it, change your code and move static variable to Sub and comment it in super. – kosa Jun 11 '14 at 19:11
  • 1
    Please make more of an effort to format your code in future, by the way. – Jon Skeet Jun 11 '14 at 19:12
  • Interestingly enough, if you run `javap -c Test` on this, it says it's getting the static `Field Sub.ID:Ljava/lang/String;`! – yshavit Jun 11 '14 at 19:12
  • Yes same for me. Showing `//Field test/Sub.ID:Ljava/lang/String;` with java7. – Aniket Thakur Jun 11 '14 at 19:17
  • So looks like sub class is in fact loaded but not initialized. – Aniket Thakur Jun 11 '14 at 19:40

0 Answers0