• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Kathy Sierra Chapter 2 Selftest Question 13

 
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Ranch Hand
Posts: 521
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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....
 
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic