java重点知识理解案例:接口回调——先有使用者,后有实现者

接口定义

package com.qf.java.interfacecallback;

/**
 * @author RBP
 *
 * @param <T>
 * 接口标准,排序。只有实现了接口的类才可以排序
 * 前者大于后者 return 正数
 * 前者小于后者 return 负数
 * 前者等于后者 return 0
 */
public interface Comparable<T>{
	//用以排序的规则制定方法。限制实现类
	public abstract int compareTo(Student stu);
	
}

Student类 ----实现类

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);
		}
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值