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

Inheritance

 
Aparna Shatdarsanam
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Q: What is the output ???

can someone explain why the output is not
Value of b = 127
Value of b = 126
but it is
Value of b = 0
Value of b = 126
[ Jess added UBB [code] tags to preserve white space, check 'em out! ]
[ January 07, 2003: Message edited by: Jessica Sant ]
 
Nayanjyoti Talukdar
Ranch Hand
Posts: 71
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Aparna,
That's a fantastic question..I was amazed to see the output. U are instantiating the Processor class from main method of Q40, so it calls the constructor of Processor, that in turn calls the super class constructor since Processor is extended from Q40. So before initialization, it calls the super class constructor where it calls the methodA using the current object. The current object is Processor object, so it calls the method called mathodA() in Processor.Here "this.b" displays 0 since the class variable initialization is not occured. The other part is quite obvious.
Hope, this helps!!
---------
Nayan
 
Jose Botella
Ranch Hand
Posts: 2120
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch Aparna.
I will elaborate a bit more the response because I liked the question:
The compiler places the code that initializes the instance variables within the constructor, between the explicit/implicit invokation to the parent constructor and the rest of the code in the constructor. That is like this:

This is helpful to get the order of initialization.
______________________________________________
The access to a variable is based on the compile type of the variable, only methods are polymorphic. "this.b" in Processor.methodA() refers to the variable b declared in Processor class. The mentioned b is hidding access to b in Q40. To access it "super.b" will print 127.
_______________________________________________
The example also shows why it is not a good idea to make polymorhic calls within a constructor. The overridding method ,"Process.methodA", could access a variable in the subclass, "Process.b", that is not yet initialized at the time of the execution of the parent constructor. Thus, it prints its default value "0".
 
Aparna Shatdarsanam
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks so much for your answers.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic