Java Reference
In-Depth Information
public class Secretary {
copy all the methods from the Employee class.
// this is the only added behavior
public void takeDictation() {
System.out.println("I know how to take dictation.");
}
}
Fortunately, Java provides a mechanism called inheritance that can help us remove
this sort of redundancy between similar classes of objects. Inheritance allows the pro-
grammer to specify a relationship between two classes in which one class includes
(“inherits”) the state and behavior of another.
Inheritance (Inherit)
A programming technique that allows a derived class to extend the func-
tionality of a base class, inheriting all of its state and behavior.
The derived class, more commonly called the subclass, inherits all of the state and
behavior of its parent class, commonly called the superclass.
Superclass
The parent class in an inheritance relationship.
Subclass
The child, or derived, class in an inheritance relationship.
We say that the subclass extends the superclass because it not only receives the
superclass's state and behavior but can also add new state and behavior of its own.
The subclass can also replace inherited behavior with new behavior as needed, which
we'll discuss in the next section.
A Java class can have only one superclass; it is not possible to extend more than
one class. This is called single inheritance. On the other hand, one class may be
extended by many subclasses.
To declare one class as the subclass of another, place the extends keyword fol-
lowed by the superclass name at the end of the subclass header. The general syntax is
the following:
public class <name> extends <superclass> {
...
}
We can rewrite the Secretary class to extend the Employee class. This will cre-
ate an is-a relationship in which every Secretary also is an Employee . Secretary
 
Search WWH ::




Custom Search