Java Reference
In-Depth Information
Notice that the first four methods produce the same output for both objects, because
Secretary inherits that behavior from Employee . The fifth line of Secretary output
reflects the new extended behavior of the takeDictation method.
Overriding Methods
We can use inheritance in our other types of Employee s, creating Lawyer ,
LegalSecretary , and Marketer classes that are subclasses of Employee . But while
the Secretary class merely adds behavior to the standard Employee behavior, these
other classes also need to replace some of the standard Employee behavior with their
own. Lawyers receive three weeks of vacation and use a pink form to apply for vaca-
tion, and they know how to handle lawsuits. Legal secretaries receive $45,000 a year
(a $5,000 raise over the standard amount), they know how to take dictation (like reg-
ular secretaries), and they can file legal briefs. Marketers receive $50,000 a year (a
$10,000 raise over the standard amount), and they know how to advertise.
We'd like these new classes to inherit most of the behavior from the Employee
class, but we need to change or replace certain parts of the behavior. It's legal to
replace superclass behavior by writing new versions of the relevant method(s) in the
subclasses. The new version in the subclass will replace the one inherited from
Employee . This idea of replacing behavior from the superclass is called overriding.
Override
To implement a new version of a method to replace code that would otherwise
have been inherited from a superclass.
To override a method, just write the method you want to replace in the subclass.
No special syntax is required, but the method's name and signature must exactly
match those of the method from the superclass.
Here is the Lawyer class that extends Employee and overrides the relevant methods:
1 // A class to represent lawyers.
2 public class Lawyer extends Employee {
3 // overrides getVacationDays from Employee class
4 public int getVacationDays() {
5 return 15;
6 }
7
8 // overrides getVacationForm from Employee class
9 public String getVacationForm() {
10 return "pink";
11 }
12
 
Search WWH ::




Custom Search