This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Kathy Sierra Chapter 2 Selftest Question 13 Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Kathy Sierra Chapter 2 Selftest Question 13" Watch "Kathy Sierra Chapter 2 Selftest Question 13" New topic
Author

Kathy Sierra Chapter 2 Selftest Question 13

Edward Seager
Greenhorn

Joined: Jan 02, 2010
Posts: 9
Hi,

I'm struggling to understand exactly how the following code is working, regarding inheritance and instance variables.



I thought this code would not compile because Zebra inherits name from Mammal but then redefines it, i.e. using the keyword String before name again.

However, the code runs and prints "furby bray" because instance variables are not overriden but methods are.

I would be very greatful if someone could clarify why it is OK to redefine inherited instance variables, as you cannot redefine variables in the same class. E.g The following code does not compile.


Also, where does the book mention that instance variables are not overriden in Chapter 2?

Thanks


Eddy Seager
Raju Champaklal
Ranch Hand

Joined: Dec 10, 2009
Posts: 521
dude...here the zebra class inherits the member string variable name from its parent class...and you are free to redefine it in your own class if you want....the only difference between inheriting superclass instance methods and variables is that overriding rules only apply to methods and not to variables....and m.name calls the mammals class variable because which instance variable to call depends on the reference variable.....and m.makeNoise() calls the method of zebra becuase which method to call depends on the object at runtime....


scjp 1.6 91%, preparing for scmad
"Time to get MAD now.. we will get even later"....by someone unknown
Dimple John
Greenhorn

Joined: Dec 08, 2009
Posts: 14
This is called Field hiding. there are no restrictions in hiding of fields. The type of the fields need not be the same either.It is only field name that matters in hiding of fields.
 
Don't get me started about those stupid light bulbs.
 
subject: Kathy Sierra Chapter 2 Selftest Question 13
 
Similar Threads
Upcasting doesn't work as intended; clarification needed
Question in scjp study guide (Kathey & Bates) page 181- oo Concepts
output of program?
instance variable inheritance
I need to help with the question 13 chapter 2