接口的关键字interface声明一个接口,一个类可以用implements关键字来实现接口中的一些方法。
这里就拿比较的接口Comparable来举例,细细体会接口对于降低代码耦合度的作用。
声明Compare接口
public interface Comparable {
public int compareTo(Object o);
}
在一个类中实现接口的compareTo方法
public class Teacher implements Comparable {
int no;
String name;
public Teacher(int no, String name) {
this.no = no;
this.name = name;
}
public void print() {
System.out.println("Student [no=" + no +
", name=" + name + "]");
}
public int compareTo (Object o) {
return no - ((Teacher)o).no;
}
}
归并排序类,里面实现了排序方法。
public class MergeSort {
public static void Sort(Object[] a) {
int len = a.length;
MS(a, 0, len - 1);
}
private static void MS(Object[] a, int L, int R) {
if(L >= R) return;
int mid = (L+R) / 2;
MS(a, L, mid);
MS(a, mid+1, R);
Merge(a, L, mid, R);
}
private static void Merge(Object a[], int L, int m, int R) {
int n = R, i = L, j = m+1;
Object t[] = new Object[a.length];
int cur = L;
while(i <= m && j <= n) {
if(((Comparable)a[i]).compareTo(a[j]) <= 0) { // 注意这里的写法,强制转换成Compare类,可以使用compareTo()方法,但这个方法的具体作用还要看传入的的Object的类中对compareTo是怎么实现的。
t[cur++] = a[i++];
}
else t[cur++] = a[j++];
}
while(i <= m) t[cur++] = a[i++];
while(j <= n) t[cur++] = a[j++];
for(int z = L; z <= R; z++) {
a[z] = t[z];
}
}
}
使用方法
public class Main {
public static void main(String[] args) {
MergeSort op = new MergeSort();
Teacher[] ss = {
new Teacher(2,"b"),
new Teacher(5,"e"),
new Teacher(3,"a"),
new Teacher(1,"f")
};
op.Sort(ss);
for (Teacher s : ss) {
s.print();
}
}
}