File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Please explian the output ....

 
Sai Charan
Greenhorn
Posts: 22
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 11343
Java Mac Safari
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
See if this helps...

If it still doesn't make sense, search for "static block" and "initializer block."
 
Sai Charan
Greenhorn
Posts: 22
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 175
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 11343
Java Mac Safari
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 22
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Marc for the help and clarification.
 
Don't get me started about those stupid light bulbs.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic