interface Collection {
...
int size();
...
}
interface List extends Collection {
...
}
interface Set extends Collection {
...
}
class Vector implements List { // ... and thus also Collection
...
}
class HashSet implements Set { // ... and thus also Collection
...
}
Collection c = new HashSet(); // upcast-- legal-- HashSet implements Collection and therefore is a Collection System.err.println(c.size());Which size gets called?
size method of HashSet is invoked.
Thus, if we then write
c = new Vector(); // upcast-- legal-- Vector implements Collection and therefore is a Collection System.err.println(c.size());the
size method of Vector is invoked.
Revisiting the Employee Class
We can examine polymorphism in the Employee class presented in the context of abstract classes.
abstract class Employee {
Employee(Name name, String ssNum) {...}
...
abstract void doPayroll();
...
Name name;
String ssNum;
Date hiredOn;
}
class FactoryWorker extends Employee {
FactoryWorker(Name name, String ssNum, Currency hourlyRate) {
super(name, ssNUm);
this.hourlyRate = hourlyRate;
}
...
void doPayroll() {
...
}
...
...
double hourlyRate;
}
class OfficeWorker extends Employee {
OfficeWorker(Name name, String ssNum, Currency annualSalary) {
super(name, ssNUm);
this.annualSalary = annualSalary;
}
...
void doPayroll() {
...
}
...
Currency annualSalary;
}
Now suppose we have an array of all the employees in the company:
Employee [] employees; ... for (int i = 0; i < employees.length; i++) employees[i].doPayroll();If a particular
employees[i] is a FactoryWorker, then the doPayroll of
the FactoryWorker class will be invoked; on the other hand, if an employees[i]
is an OfficeWorker, then the doPayroll of the OfficeWorker class will be invoked.