Debugging sub-expression
Sub.x
in expression
System.out.println(Sub.x);
in given below code,to understand rule of class initialization in run-time for classes namely., class Sub and class Super in JVM memory space.
package defaultvalues; import java.util.*; class Super{ static int x; static{ System.out.println("Super"); } } class Sub extends Super{ Date date; {//instance initialisation block for date Calendar temp = Calendar.getInstance(); date = temp.getTime(); } static{ System.out.println("Sub"); } long alarm; } class Game{ static Random rand; static{ rand = new Random(); } static void tossCoin(){ if(rand.nextBoolean()){ System.out.println("Heads"); }else{ System.out.println("Tails"); } } } public class Example { public static void main(String[] args) { System.out.println(Sub.x); // class Super is loaded. From class Super, static members are //initialised and static initialisation blocks are executed before executing expression 'Sub.x' Game.tossCoin(); // class Game is loaded. From class Game, static members are initialised //and static initialiser blocks are executed before executing expression 'Game.tossCoin()' Sub obj = new Sub(); //instance variables are initialised and instance initialisation block //of class A are executed. System.out.println(obj.date); System.out.println(obj.alarm); } } After debug, observation is that, class Super gets initialized but class Sub does not get initialised before expression Sub.x gets evaluated. Immediate output after evaluating expression System.out.println(Sub.x); is:
Super 0 So, System.out.println("Sub"); does not execute before expression Sub.x gets evaluated.
With respect to this expression Sub.x evaluation, in source code, I see the expression Sub.x getting evaluated, class Super gets initialized but not class Sub.
My question is:
Does class Sub get loaded & linked but not initialized before evaluating sub-expression Sub.x during run-time?
Note: Working in Eclipse environment
xis being accessed through a sub class?javap -c Example.classfrom the console and see.javapshows this:3: getstatic #22; //Field defaultvalues/Sub.x:IHow do I understand this line?Sub.xof typeInteger.Sub.xwithSuper.x, then, whyclass Subdoes not get loaded before sub-expressionSub.xgets evaluated?