This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
I'm just playing around with some code and notice the following...
Private fields are not inherited. When I try to access a private field from an extended class, it's not visible. That's fine. But why does my IDE recommend creating a getter for the field, within the super? After I did this, the errors went away. Why am I able to reference my super's private field, just by creating a getter within the super class?
So when I call my subclass' getter, it actually calls the getter for my super? This would mean that my subclass isn't actually getting its own copy of the getter, since it wouldn't be able to access the field directly. It's just redirecting the request to the super.
Michael Novello wrote:This would mean that my subclass isn't actually getting its own copy of the getter
Correct. Inherited members are not copied. There would be no point to that.
Just as a guess, maybe you're thinking there's a "parent object" and a "child object" and inherited variables and methods are copied from the "parent object" to the "child object"? That picture of separate objects is a common misconception. There's only one object. It IS-A parent and it IS-A child, and everything that's in either parent or child is present in that one object.
Joined: Mar 03, 2013
What about instance variables that are inherited? If they aren't copied, how do the objects keep track of their own values? Thanks for your help. Is there somewhere I can read more about the internals of this mechanism?
An object is really an "onion" like thing, with multiple layers.
An object that's an instance of a subclass consists of an instance of its superclass, with the member variables that are declared in the subclass added to it.
By the way, I don't like using the words "Parent" and "Child" for superclasses and subclasses. It confuses the biological meaning of the word "inheritance" with the meaning of the word in object oriented programming. In biology, "inheritance" means that the child copies traits from its parents. In object oriented programming, "inheritance" means "specialization", and there's an "is a" relationship.
An instance of a subclass is a (specialized) version of an instance of the superclass.
If you're using the names "Parent" and "Child" for classes, you're saying "a Child is a Parent", which is weird. I am not my father...
Better naming would be for example to use Animal and Dog. A Dog is an Animal. When you have a Dog, it has all the member variables and methods that an Animal has, with additional member variables and methods that only a Dog has, added to it.