File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Inheritance Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Inheritance" Watch "Inheritance" New topic


Aparna Shatdarsanam

Joined: Nov 28, 2002
Posts: 9
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

Joined: Feb 12, 2002
Posts: 71
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!!
Jose Botella
Ranch Hand

Joined: Jul 03, 2001
Posts: 2120
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".

SCJP2. Please Indent your code using UBB Code
Aparna Shatdarsanam

Joined: Nov 28, 2002
Posts: 9
Thanks so much for your answers.
I agree. Here's the link:
subject: Inheritance
It's not a secret anymore!