Java Reference
In-Depth Information
Of course, ideally we would like to output the member, type , of the base class, but we can't reference
this in the derived class, because it is not inherited. However, we can still call the base class version of
toString() . It's another job for the super keyword.
Try It Out - Calling a Base Class Method from a Derived Class
We can rewrite the derived class version of toString() to call the base method:
// Present a dog's details as a string
public String toString() {
return super.toString() + "\nIt's " + name + " the " + breed;
}
Running the example again will produce the output:
This is a Dog
It's Fido the Chihuahua
This is a Dog
It's Lassie the Unknown
How It Works
The keyword super is used to identify the base class version of toString() that is hidden by the
derived class version. We used the same notation to refer to superclass data members that were hidden
by derived class data members with the same name. Calling the base class version of toString()
returns the String object for the base part of the object. We then append extra information to this
about the derived part of the object to produce a String object specific to the derived class.
Choosing Base Class Access Attributes
You now know the options available to you in defining the access attributes for classes you expect to use
to define subclasses. You know what effect the attributes have on class inheritance, but how do you
decide which you should use?
There are no hard and fast rules - what you choose will depend on what you want to do with your
classes in the future, but there are some guidelines you should consider. They follow from basic object
oriented principles:
The methods that make up the external interface to a class should be declared as public . As long
as there are no overriding methods defined in a derived class, public base class methods will be
inherited and fully available as part of the external interface to the derived class. You should not
normally make data members public unless they are constants intended for general use.
If you expect other people will use your classes as base classes, your classes will be more
secure if you keep data members private , and provide public methods for accessing and
manipulating them. In this way you control how a derived class object can affect the base class
data members.
Search WWH ::




Custom Search