package com.qf.java.interfacecallback;
/**
*Student实现Comparable接口
*
*/
public class Student implements Comparable<Object> {
String name; //成员属性姓名
int age; //成员属性年龄
double score; //成员变量成绩
//无参构造
public Student() {}
//有参构造
public Student(String name, int age, double score) {
super();
this.name = name;
this.age = age;
this.score = score;
}
//实现接口的抽象方法。定义排序的规则
public int compareTo(Student stu) {
if (this.score > stu.score) {
return 1;
}else if (this.score < stu.score) {
return -1;
}
return 0;
}
}
工具类—Tool
package com.qf.java.interfacecallback;
public class Tool {
//用sort排序
public static void sort(Student[] stus){
for (int i = 0; i < stus.length-1; i++) {
//强制类型转换
Comparable currentStu = (Comparable)stus[i];
//student即是调用者也是实现者
int n = currentStu.compareTo(stus[i+1]);
//互换位置
if (n > 0) {
Student temp = stus[i+1];
stus[i+1] = currentStu;
currentStu = temp;
}
}
}
}
测试类
package com.qf.java.interfacecallback;
public class TestStudent {
/**
* @param args
* 先有了接口的使用者,后有了接口的实现者
*/
public static void main(String[] args) {
//创建学生数组并赋值
Student[] students = new Student[]{
new Student("tom", 14, 80),
new Student("jack", 16, 75),
new Student("rose", 12, 90)};
//类名调用静态方法
Tool.sort(students);
//遍历输出
for (int i = 0; i < students.length; i++) {
System.out.println(students[i].score);
}
}
}