| Author |
Please explian the output ....
|
Sai Charan
Greenhorn
Joined: Apr 24, 2006
Posts: 22
|
|
class Bird { { System.out.print("b1 "); } public Bird() { System.out.print("b2 "); } } class Raptor extends Bird { static { System.out.print("r1 "); } public Raptor() { System.out.print("r2 "); } { System.out.print("r3 "); } static { System.out.print("r4 "); } } class Hawk extends Raptor { public static void main(String[] args) { System.out.print("pre "); new Hawk(); System.out.println("hawk "); } }
|
 |
marc weber
Sheriff
Joined: Aug 31, 2004
Posts: 11343
|
|
See if this helps... If it still doesn't make sense, search for "static block" and "initializer block."
|
"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
|
 |
Sai Charan
Greenhorn
Joined: Apr 24, 2006
Posts: 22
|
|
Thanks Marc. I understand this, but one confusing part to post this Q basically is: why "In main: Creating new Hawk..." is NOT displayed at the Beginning of the output? Please someone explain. Thnaks output: ------ First static block in Raptor. Second static block in Raptor. In main: Creating new Hawk... Initializer block in Bird. Bird constructor. Initializer block in Raptor. Raptor constructor. In main: Hawk created.
|
 |
aymane chetibi
Ranch Hand
Joined: Apr 12, 2006
Posts: 175
|
|
Hi, I tried the following code: with an empty main, and the output was everything that was in the static blocks. So I think that static blocks wherever they are are executed before the main. ( Is that due to the fact that Java is both interpreted and compiled ?) regards,
|
 |
marc weber
Sheriff
Joined: Aug 31, 2004
Posts: 11343
|
|
Originally posted by Sai Charan: ...one confusing part to post this Q basically is: why "In main: Creating new Hawk..." is NOT displayed at the Beginning of the output? ...
One thing that causes classes to be loaded is accessing a static member. And static blocks execute when the class is loaded. In this case, Hawk's static method main is invoked from the command line, which loads the class Hawk along with its superclasses. This is why the static block in Raptor executes (at class load time) even before the body of Hawk's main method is executed.
|
 |
Sai Charan
Greenhorn
Joined: Apr 24, 2006
Posts: 22
|
|
|
Thanks Marc for the help and clarification.
|
 |
 |
|
|
subject: Please explian the output ....
|
|
|