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 of instance variable 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 of instance variable" Watch "Inheritance of instance variable" New topic

Inheritance of instance variable

ali kamran

Joined: Apr 25, 2010
Posts: 29
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

Joined: Jan 28, 2008
Posts: 5575

Please, QuoteYourSources .
ali kamran

Joined: Apr 25, 2010
Posts: 29
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

Joined: Feb 24, 2006
Posts: 6662

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.

SCJP 6 articles - SCJP 5/6 mock exams - More SCJP Mocks
Alexandre Leveille

Joined: Jan 26, 2013
Posts: 12

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

Joined: Feb 06, 2013
Posts: 2
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
It is sorta covered in the JavaRanch Style Guide.
subject: Inheritance of instance variable
It's not a secret anymore!