Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Object creation..?

 
santhosh.R gowda
Ranch Hand
Posts: 296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

The output is i===0
Please conclude the output
 
Till Stoschus
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
At this time, i in test is 0.

Please justify the above statement
 
Matthew Cox
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 449
IntelliJ IDE Java Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic