As you probably guessed, the solution is to use interfaces
instead of classes.
Here's an interface called Sortable:
package sortable;
public interface Sortable
{
public int compare(Sortable rhs);
}
|
We have to place the shellSort() method in a separate class, because Java doesn't
let us implement any methods in an interface:
package sortable;
public abstract class Sort
{
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;
}
}
}
|
Note that we made class Sort abstract, because we never need an instance of
it; it contains exactly one method, which is a static method. (Another
example of an abstract class that only contains static methods is the Math
class.)
And we must then modify the Employee class as
follows:
package Employees;
import java.util.Date;
import Sortable.Sortable;
public class Employee implements Sortable
{
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;
}
// ...
}
|
Note that we use the implements keyword to specify that a class
uses an interface, as opposed to the extends keyword.
The test code looks similar to before:
package company;
import java.util.Date;
import sortable.Sort;
public class CompanyTest
{
public static void main(String[] args)
{
Employee[] staff = new Employee[6];
// ...
Sort.shellSort(staff);
for (int i = 0; i < staff.length; i++)
staff[i].print();
}
}
|
|