• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Initialization blocks...

 
sonia jaswal
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Given:

class Bird {
{ System.out.print("bl "); }
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 ");
}
}

Output:

r1 r4 pre b1 b2 r3 r2 hawk

//Shouldn't the ouput of the code be r2 first and then r3....
 
Satya Maheshwari
Ranch Hand
Posts: 368
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Since Instance initializer blocks are executed prior to constructors, 'r3' is printd before 'r2'
 
sonia jaswal
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks for the reply....
 
Hamraj Kulshreshtha
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Since the instance init blocks run right after the call to super() in
a constructor,so r3 will be printed first and then r2.

And if more than one init blocks(Static or Instance) occurs in a class they run in the same order as they are defined i.e. from top to down.

Regards,
Hamraj
 
Bert Bates
author
Sheriff
Posts: 8898
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Sonia,

It's great to post mock exam questions on this forum for discussion purposes, so please carry on! However, in respect to all authors of mock exam questions, please indicate in your posts where each question came from. (In this case this is one of my questions, so no need in this case - but in the future.)

Thanks,

Bert
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic