aspose file tools*
The moose likes Beginning Java and the fly likes Object creation..? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Object creation..?" Watch "Object creation..?" New topic
Author

Object creation..?

santhosh.R gowda
Ranch Hand

Joined: Apr 06, 2009
Posts: 296

The output is i===0
Please conclude the output


Creativity is nothing but Breaking Rules
Till Stoschus
Greenhorn

Joined: May 28, 2009
Posts: 14
Hi,

my output is

i===0
i===20

The call of show() in the superclass test1 calls the show-Method of class test. At this time, i in test is 0.

Tillux
santhosh.R gowda
Ranch Hand

Joined: Apr 06, 2009
Posts: 296
At this time, i in test is 0.

Please justify the above statement
Matthew Cox
Greenhorn

Joined: May 25, 2009
Posts: 29
santhosh.R gowda wrote:
At this time, i in test is 0.

Please justify the above statement


The reason this occurs has to do with what is going on behind inheritance. I am going to refer to "test" as "testD" (Derived) and "test1" as "testS" (Super) to keep the meaning clearer about your classes.

When you instantiate testD, the first line executed (regardless of whether you type it or not is super();) inside of the constructor. So at the very beginning of the constructor of testD, i is =0. This is because before any assignments or code in testD can be executed, the super type must be created first. So, in testS, i is set to 10. BUT, since you have declared a variable type/name that is identical in the super class, the testS i variable is hidden. When show() is called inside of the testS constructor, no explicit call for testS i is made ... just simply the following:

System.out.println("i===" + i); //which i are you referring to? The compiler refers to the one that is not hidden, meaning testD's i, which at the moment = 0.

From there I think you can understand what is going on.

Here is an example that will show the correct output for each value.




There are a few other approaches to ensure the desired output but this is a easy concrete way to approach the problem.
Muhammad Khojaye
Ranch Hand

Joined: Apr 12, 2009
Posts: 449

Calling overridable methods during construction always poses a risk. If the default constructor contains a call to an overridable method, the subclass may be completely uninstantiable.

I have modified the code slightly, and see how it generate Null Pointer Exception.



http://muhammadkhojaye.blogspot.com/
 
Consider Paul's rocket mass heater.
 
subject: Object creation..?