I have a question too... (I have no problem with the output that I ran)
When the control enters main...should it now first see the print statement and print "pre" and continue with the rest of the output?
Then when it sees new C() .... call the contructor of B which in turn calls A's contructor.
Can somebody please reiterate the rules for running static/initialization block and contructors.
I think I've figured out what's happening an how it's happening..
One thing is sure that before running the child class's constructor one of the constructors of the parent class must be executed.
When the class C is compiled,at that time B is also compiled and so is A class.
now when the class C is executed, then class B is loaded in to the memory.
Static blocks are executed, when the class is loaded in to the memory.
That's why r1 and r2 are printed first.(No constructor is executed yet!!!)
Now, the control is back to the System.out.println("pre"); statement of C class.
then "pre" is printed.
Now when C's constructor is executed, B's constructor must be executed which in turn invokes A's constructor.
As class A has a initialization block,that must be executed first before running it's constructor.
When the class is loaded JVM will initialize the class at any of the following conditions.
If the static method of the class is called inthis case main
If the instance of the class is created
If the static variable is assigned a value.
If the non compile time constant is accessed
So in this case class C's main method is called by JVM so it has to initialize C but since C also extends B which extends A it will initalize the super class B and A before C .
Once it initializes all the class members and run static initalizer blocks in the upper tree it will now enter into main method and print pre then we are creating C instance which will call super constructor till Object and executes the initalizer and initializer block from Object to C.
Hope it helps.
SCJP 6,SCWCD 5,SCBCD 5
Failure is not an option.
Joined: Jul 22, 2009
Thank you all for immediate response . If I use NetBeans for any program will it display any different output? Except this which I mentioned the above one I never get any problem so far.
There is only one command in to run a program( shift+f6) in NetBeans. It does n't have any separate command to compile.
I don't know is there any option to run a program at command line with NetBeans tool.
I don't think it should alter the output however I haven't tried the code in NetBeans. I also agree with Ankit that instead of using an IDE you should use the commandline for compiling and running the program.
i have the same problem (output "pre post") in Eclipse. But output is correct when moving the definition of class B to a separat file. There are some posts on Eclipse forums about that. I cannot explain this strange behavior. Dont use IDE in exam prep. Dont put multiple classes in one file when using an IDE.