|
What's The Problem? The Solution Why Is That Better? Multiple Inheritance What is an Interface? Nouns vs. Adjectives Interface Inheritance Marker Interfaces
| | Suppose you wanted your employee classes to
have a standard behavior, such as the ability to be sorted -- so that you
could list your employees in a report, perhaps.
You could add this capability to the Employee class, and all its subclasses would inherit that
capability, also.
On further reflection, however, you realize
that the capability of being sorted is potentially usable by
other classes beyond just employees.
So, you write an abstract class Sortable:
package sortable;
public abstract class Sortable
{
public abstract int compare(Sortable rhs);
public static void shellSort(Sortable[] a)
{
int n = a.length;
int incr = n/2;
while (incr >= 1)
{
for (int i = incr; i < n; i++)
{
Sortable temp = a[i];
int j = i;
while ((j >= incr) &&
(temp.compare(a[j - incr]) < 0)
)
{
a[j] = a[j - incr];
j -= incr;
}
a[j] =temp;
}
incr /= 2;
}
}
}
|
And modify the Employee class to inherit
from it:
package company;
import java.util.Date;
import sortable.Sortable;
public class Employee extends Sortable
{
// Compare, based on salary
public int compare(Sortable rhs)
{
Employee eb = (Employee) rhs;
if (m_salary < eb.m_salary) return -1;
if (m_salary > eb.m_salary) return 1;
return 0;
}
// ...
}
|
Then, we can modify the test program to use
the sorting capability:
package company;
import java.util.Date;
import sortable.Sortable;
public class CompanyTest
{
public static void main(String[] args)
{
Employee[] staff = new Employee[6];
// ...
Sortable.shellSort(staff);
for (int i = 0; i < staff.length; i++)
staff[i].print();
}
}
|
This works fine.
|