Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

doubt

 
Sakthi Kani
Ranch Hand
Posts: 98
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi



The output is 0 and 16.
why not a=10 ???
explain.....
 
Vishnu Prakash
Ranch Hand
Posts: 1026
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The output should be b=0 and b=16

when u instantiate "Q05" the constructor of this class is called.
From there the super class constructor is called. when you call the
method "call" from the super class constructor it is the subclass overridden
"call" which is invoked and not the super class version of "call". This is because
you had instantiated the subclass and at runtime the subclass version of
the "call" will be invoked.

Why b = 0?

because instance variables will not be initialized with values
(here b = 16) but given default values which is 0 for int until after
super class constructor completes it execution. once it is over and it
comes to subclass constructor and makes a call to the method "call"
by now b will be initialized with 16 so the second value will be 16.


Since super class version of call is never called "a" is never printed
 
miguel lisboa
Ranch Hand
Posts: 1281
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
constructors are not inherited, i guess
 
vidya sagar
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
HI sakthi

By executing the statement new Q05()
(Let see step by step)

step - 1 calls constructor of Q05 class
(every first line in constructor calls to its immediate base class)

step - 2 which in tends call to Just class constructor

step - 3 which in tends call to Object class constructor

step - 4 object class constructor returns

step - 5 method name call() in just class executes call() method in Q05 class
(at that time b only contains default value...so it prints 0)
(Initialize of instance variables takes place only after base class constructor completes)
(derived class method is called because instance is of derived class)

step - 6 Just class constructor returns

step - 7 method name call() in Q05 class constructor executes call() method in Q05 class
(this time given b value is intialized to 16....so it prints 16)

Hope now UR clear
 
Sakthi Kani
Ranch Hand
Posts: 98
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank u
i got the point now
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic