Re: Puzzling class field initialization order
Mark Gorokhov <[email protected]>
| Newsgroups | gmane.comp.windows.devel.java.advanced |
|---|---|
| Message-ID | <6BD989BB73712F41B1EDD1B8A32EA4C3074B955A@EXCHANGEVS1.comtechtel.com> |
Interesting, commenting out "C c = new C();" prints both not null.
X.java:
=======
public class X {
public static void main(String[] args) {
//C c = new C();
System.out.println(S.IMPL);
System.out.println(I.IMPL);
}
}
-mg
-----Original Message-----
From: Discussion of advanced Java topics.
[mailto:[email protected]] On Behalf Of Attila Szegedi
Sent: Thursday, September 06, 2007 9:22 AM
To: [email protected]
Subject: [ADVANCED-JAVA] Puzzling class field initialization order
Hi folks,
I observed an interesting behaviour in initialization of static fields,
and am unable to understand it. Can anyone help? Here's the code
distilled
to absolute minimum demonstrating the problem, in four classes:
S.java:
=======
class S {
static final C IMPL = C.INSTANCE;
}
I.java:
=======
interface I {
static final C IMPL = C.INSTANCE;
}
C.java:
=======
class C extends S implements I {
static final C INSTANCE = new C();
}
X.java:
=======
public class X {
public static void main(String[] args) {
C c = new C();
System.out.println(S.IMPL);
System.out.println(I.IMPL);
}
}
Running X prints null for S.IMPL, as expected, since S.IMPL was
initialized before C.INSTANCE when C was loaded. That's perfectly
understandable.
*However* it prints a non-null instance for I.IMPL, i.e. "C@2e7263"!
Now,
anyone care to explain why isn't I.IMPL null as well? It is likely
something related to a difference in loading a superclass vs. loading a
superinterface, but if anyone has a definitive explanation (a pointer to
the relevant JVM spec section will suffice :-)), I'd appreciate that.
BTW, Java runtime version is:
java version "1.5.0_07"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_07-164)
Java HotSpot(TM) Client VM (build 1.5.0_07-87, mixed mode, sharing)
Thanks,
Attila.
--
home: http://www.szegedi.org
weblog: http://constc.blogspot.com
===================================
This list is hosted by DevelopMentor(r) http://www.develop.com
View archives and manage your subscription(s) at
http://discuss.develop.com
===================================
This list is hosted by DevelopMentor® http://www.develop.com
View archives and manage your subscription(s) at http://discuss.develop.com