• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Inheritance of instance variable

 
ali kamran
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
Quick question as follows

Now I understand Variables are not inherited so gc1.i should print 1 which it does but why does the constructor print i as 9 from the grandchild ? Anyone,Thanks much appreciated.
 
Seetharaman Venkatasamy
Ranch Hand
Posts: 5575
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please, QuoteYourSources .
 
ali kamran
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Seetharaman Venkatasamy wrote:Please, QuoteYourSources .


I read in Kathy sierra that variables are not inherited so came up with the example to do this and earlier had the i as protected to showcase i can be accessed only via constructor and nowhere else and then I thought what if we had a constructor that would call the i which would it print .To cut a long story short experiment with what I have iterated to this point .
 
Deepak Bala
Bartender
Posts: 6663
5
Firefox Browser Linux MyEclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It has to do with scoping. Variables with the most local scope are picked up first.

Local variables -> My member variables -> Parent member variables -> Something up the hierarchy

In the example below, 'i' first resolves to 9 and then to 10. The code picks up 10 since it can resolve it locally.

 
Alexandre Leveille
Greenhorn
Posts: 12
Android Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As Deepak said, the JVM will use the "closest" variable. If you shadow the member's variable with a local variable, you'll see just how the JVM resolves which variable it uses. Also comment the lines 2, 5 and/or 20 in the below code to get a better understanding of the difference between no prefix (just "i"), this.i and super.i.


 
Jenson Joseph
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here at line # 9, gc1 is of type Parent and constructor grandchild() is called. Hence in constructor it will print i=9, but later gc.i will be 1 as its type is Parent. if its type is changed from Parent to grandchild, it wil print gc.i=9


now the output will be 9
child9
.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic