This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
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 ]
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
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".