之前学习的那些,自我感觉挺良好,但是在学习了接口之后,深切体会了这是个脑力活动,挺难理解,而且讲师也讲了两节课来帮我们巩固,自己又翻了翻,这是个很重要的内容,Java接口是一系列方法的声明,是一些方法特征的集合,一个接口只有方法的特征没有方法的实现,为了减少代码的耦合程度,接口是个非常非常非常便利的工具,定义一个能力,然后写一个实现类来实现他,之后有个使用者来进行调用。
这是一个利用接口来实现排序的一个案例
/**
* 接口回调
*
* * 程序员 */
public class TestCallback {
public static void main(String[] args){
//需求:对一组学生对象排序
Student[] students = new Student[] { new Student("tom",20,"male",99.0) , new Student("jack",21,"male",98.0) , new Student("annie",19,"female",100.0)};
//工具调用者
Tool.sort(students);
//默认升序
for (int i = 0; i < students.length; i++) { System.out.println(students[i].name +"\t"+ students[i].score); } }}
//学生类
class Student implements Comparable<Student>{
//接口的实现者
String name;
int age;
String sex;
double score;
public Student() {}
public Student(String name, int age, String sex, double score) { super();
this.name = name;
this.age = age;
this.sex = sex;
this.score = score; }
@Override
public int compareTo(Student stu) {
//升序
if(this.score > stu.score) {
return 1; }
else if(this.score < stu.score) {
return -1;
}
return 0;
}
}
工具:
/** * 工具 * 我(郑老师) */
public class Tool {
/** * 排序方法:可以帮助任何类型的一组对象做排序 */ public static void sort(Student[] stus) {
//tom 99 jack 98 annie 100
for(int i = 0 ; i < stus.length - 1 ; i++) { Comparable currentStu = (Comparable)stus[i]; int n = currentStu.compareTo(stus[i+1]);
//正数this靠后 (接口的使用者)
if(n > 0) {
//两值交换
Student temp = stus[0];
stus[0] = stus[1];
stus[1] = temp;
}
}
}
}
接口:
/** * 接口/标准(排序) * 只有现实此接口的对象,才可以排序 */
public interface Comparable<T> {
/**
* 比较的方法
* * this与传入的stu对象进行比较
* * @param stu 另一个学生对象
* * @return 标准:正数 负数 零
* * 负数:this靠前,stu靠后
* * 正数:this靠后,stu靠前
* * 零:不变
* */
public int compareTo(T stu) ;
//Student stu
}
接着之后学习了内部类,内部类又可以分类为:普通内部类,匿名内部类,局部内部类和静态内部类,然后又初识了Object类。
这是一个用匿名内部类和局部内部类调用的案例
public class TestLamp{
public static void main(String []args){
Lamp lamp=new Lamp();
//调用局部类技术,调用lamp的on方法要求输出“shine in red
class Lamp implements Light{
@Override
public void shine() {
System.out.println("shine in red");
}
}
lamp.on(new Lamp());
//调用匿名内部类技术.调用lamp的on方法要求输出”shine in yellow
lamp.on(new Light(){
public void shine(){
System.out.println("shine in yellow");
}
});
}}
interface Light{
void shine();}class Lamp{
public void on(Light light) {
light.shine();
}
}