Inheriting Components
example, imagine that you have defined some superclass that contains certain
components that you want to change in some way. If these components are
defined in the protected visibility section of the superclass, it is quite possible that
these changes cannot be carried out without affecting all of the subclasses that
may be using these components. The general rule of thumb here is to always
define attributes in the private visibility section. If
a
subclass needs to be granted
access to these components, then the access should be provided in the form of
getter/setter methods that are defined in the
PROTECTED SECTION
of the class. This
little bit of additional work ensures that a superclass is fully encapsulated.
5.2.2 Visibility of Instance Components in Subclasses
Subclasses inherit the instance components of all of the superclasses defined in
their inheritance tree. However, not all of these components are visible at the sub-
class level. A useful way of understanding how these visibility rules work is to
imagine that you have a special instance attribute pointing to an instance of the
superclass inside of your subclass. You can use this reference attribute to access
public components of the superclass, but access to private components is
restricted just as it would be for any normal object reference variable.
As it turns out, this imaginary object reference metaphor is not too far off from
what is actually implemented in subclasses behind the scenes. Subclasses contain
a special pseudo reference variable called super that contains a reference to an
instance of an object of the superclass's type. This reference is used to access com-
ponents of a superclass inside a subclass. The primaiy difference between the
super pseudo reference variable and a normal reference variable is that the super
pseudo reference can also be used to access components defined in the
PROTECTED
SECTION
of the superclass it points to.
The use of the super pseudo reference variable is optional (as was the case with
the me self-reference variable discussed in Chapter 2, Working with Objects) but
can be used in situations where explicit reference to superclass components is
needed. Normally, you will simply access the components of the superclass
directly, but it is important to remember that the compiler is implicitly plugging
in the super pseudo reference behind the scenes to properly address these com-
ponents. If you operate in this mindset, the visibility rules for accessing super-
class components should be pretty intuitive.
135