I have a class, Super:
public class Super {
public static String foo = "foo";
}
I also have another class, Sub that extends Super:
public class Sub extends Super {
static {
foo = "bar";
}
public static void main (String[] args) {
System.out.println(Super.foo);
}
}
When I run it, it prints out bar.
My third (and last) class is Testing:
public class Testing {
public static void main (String[] args) {
System.out.println(Super.foo);
System.out.println(Sub.foo);
System.out.println(Super.foo);
}
}
This prints:
foo
foo
foo
I don’t understand why the contents of foo vary depending on what class you’re accessing it from. Can anyone explain?
Basically it’s a matter of type initialization. The value of
foois set to"bar"whenSubis initialized. However, in yourTestingclass, the reference toSub.foois actually compiled into a reference toSuper.foo, so it doesn’t end up initializingSub, sofoonever becomes"bar".If you change your Testing code to:
Then it would print out “bar” four times, because the first statement would force
Subto be initialized, which would change the value offoo. It’s not a matter of where it’s accessed from at all.Note that this isn’t just about class loading – it’s about class initialization. Classes can be loaded without being initialized. For example:
That still prints “foo” twice, showing that
Subisn’t initialized – but it’s definitely loaded, and the program will fail if you delete theSub.classfile before running it, for example.