Java Reference
In-Depth Information
Occasionally, you may want to provide clients with a class but you may
also want to prevent this class from being extended by inheritance. This
is accomplished by using the final keyword in the class declaration, as
follows:
class final Gauge
{
...
)
Now no other class can extend Gauge. Another option is to allow a
class to be extended but to prevent one or more of its methods from being
inherited by the subclasses. This is accomplished by using the final key-
word in the method declaration. For example:
class Gauge
{
...
public final SetGauge(int neddlePos)
{
If now a class extends Gauge, it does not inherit the method Set-
Gauge(). However, since SetGauge() is a public method it can be accessi-
ble to other classes.
Extending class functionality
Class inheritance is a powerful mechanism for extending class functional-
ity.Thissaid,youshouldnotethatinheritanceisusedonlyincasesinwhich
the subclass “is a kind of” the superclass. In Chapter 14 we described this
kind a class relationship as a Generalization/Specialization structure, and
called it Gen/Spec for short. That is, the subclass is a special case of the
superclass. Inheritance is not suitable when the subclass “is a part of” the
superclass, which we call a Whole/Part structure.
Programmers note:
The keyword super is used in a subclass to refer to a method of the
superclass. The super keyword is often used to call constructors of
the superclass.
Perhaps the principal feature of inheritance is that it allows reusing the
data and functionality of a superclass while permitting the subclass to de-
fine its own data and methods. If there is an inheritance hierarchy be-
tween classes, and a method is called that is not implemented in the
subclass, Java will search up the class hierarchy until a method is found
Search WWH ::




Custom Search