aspose file tools*
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


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Inheritance of instance variable" Watch "Inheritance of instance variable" New topic
Author

Inheritance of instance variable

ali kamran
Greenhorn

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

Joined: Jan 28, 2008
Posts: 5575

Please, QuoteYourSources .
ali kamran
Greenhorn

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
Bartender

Joined: Feb 24, 2006
Posts: 6657
    
    5

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
Greenhorn

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
Greenhorn

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
child9
.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Inheritance of instance variable
 
Similar Threads
Inheritance
GARBAGE COLLECTION (HFJ PG 266 )
garbage collector
Overriding private method
Garbage collection