Java Reference
In-Depth Information
19 System.out.printf("$%.2f, ", e.getSalary());
20 System.out.print(e.getVacationDays() + ", ");
21 System.out.print(e.getVacationForm() + ", ");
22 System.out.println(e); // toString representation of employee
23 }
24 }
Notice that the method lets us pass many different types of Employee s as parame-
ters, and it produces different behavior depending on the type that is passed.
Polymorphism gives us this flexibility. The last token of output printed for each
employee is the employee object itself, which calls the toString method on the
object. Our classes don't have toString methods, so the program uses the default
behavior, which prints the class name plus some extra hexadecimal characters. This
allows us to distinguish the classes in the output. The program produces output such
as the following:
40, $40000.00, 10, yellow, Employee@10b30a7
40, $40000.00, 15, pink, Lawyer@1a758cb
40, $40000.00, 10, yellow, Secretary@1b67f74
40, $45000.00, 10, yellow, LegalSecretary@69b332
The word “polymorphism” comes from the Greek words “poly” and “morph,”
which mean “many” and “forms,” respectively. The lines of code in the printInfo
method are polymorphic because their behavior will take many forms depending on
what type of employee is passed as the parameter.
The program doesn't know which getSalary or getVacationForm method to
call until it's actually running. When the program reaches a particular call to an
object's method, it examines the actual object to see which method to call. This con-
cept has taken many names over the years, such as late binding , virtual binding , and
dynamic dispatch.
When you send messages to an object stored in a variable of a superclass type, it is
legal only to call methods that are known to the superclass. For example, the follow-
ing code will not compile because the Employee class has no fileLegalBriefs
method:
Employee ed = new LegalSecretary();
ed.takeDictation("Hello!"); // compiler error
ed.fileLegalBriefs(); // compiler error
The compiler does not allow this code because the variable ed could theoretically
refer to any kind of employee, including one that does not know how to file legal briefs.
Even though we know it must refer to a LegalSecretary because the code is so sim-
ple, the compiler enforces this rule strictly and returns an error message. The same thing
happens if you write a method that accepts an Employee as a parameter; you cannot call
 
Search WWH ::




Custom Search