• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Jeanne Boyarsky
  • Ron McLeod
Sheriffs:
  • Paul Clapham
  • Liutauras Vilda
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

can anyone explain to me the output of this code

 
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
 
Rancher
Posts: 43081
77
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
That's kind of an open-ended question. Which part of the output are you having trouble understanding?
 
vuthlarhi donald
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
here is the output r1 r4 pre b1 b2 r3 r2 hawk
but I was expecting pre to be printed first!!
 
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
r1 and r4 appear before pre, since they are part of static init blocks in Raptor. They execute as soon as the class is loaded, even without an instance being created. Note that Hawk extends Raptor, so the Raptor class is loaded when you ran "java Hawk" from the command line.
 
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
r1 r4 pre b1 b2 r3 r2 hawk

Whenever a class is loaded, all the static initialiser blocks are excuted.
Next when you create an object of the class, first of all the instance initialiser blocks are executed and then constructor runs. At the time of running constructor, the implicit super() call to superclass consctrucor is invoked.

So when the classes are loaded "r1" and "r4' get printed, then at main method -> print "pre" . Then implicit constructor of Hawk calls super() to run Raptor(), which in turn calls Bird(). Before creating Bird object, the instance initialiser block is executed and "b1" gets printed. Then constructor runs and "b2" gets printed. It comes back to Raptor constructor where instance initialiser block gets excuted and "r3" is printed, then "r2" and finally "hawk" in main.
 
Paddy spent all of his days in the O'Furniture back yard with this tiny ad:
Smokeless wood heat with a rocket mass heater
https://woodheat.net
reply
    Bookmark Topic Watch Topic
  • New Topic