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 Kathy Sierra Chapter 2 Selftest Question 13 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 "Kathy Sierra Chapter 2 Selftest Question 13" Watch "Kathy Sierra Chapter 2 Selftest Question 13" New topic

Kathy Sierra Chapter 2 Selftest Question 13

Edward Seager

Joined: Jan 02, 2010
Posts: 9

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?


Eddy Seager
Raju Champaklal
Ranch Hand

Joined: Dec 10, 2009
Posts: 521 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 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" someone unknown
Dimple John

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.
I agree. Here's the link:
subject: Kathy Sierra Chapter 2 Selftest Question 13
It's not a secret anymore!