接口也是一种引用数据类型 , 它也可以声明对象 , 但是由于接口没有构造方法, 该对象不能用 new 来初始化 , 他只能存放实现该接口的类的一个实例的内存引用地址 . 

1 接口回调 

   接口回调类似于 C 语言的指针回调 ,表示一个变量的地址存放在一个指针变量中 ,那么该指针就可以对变量的数据做操作 .

java 语言中的接口回调是指把实现某一接口的类创建的对象引用赋值给该接口声明的对象 .该接口对象就可以调用被类实现的接口方法 . 

// Test.java

public static void main(String[] args) {
// TODO Auto-generated method stub
ShowBrand show ; // 创建了一个ShowBrand 接口 show
show = new TV() ; // 相当于指针show 指向了TV
show.showMessage("液晶电视");
show = new PC() ;
show.showMessage("Computer");
}
// ShowBrand.java
public interface ShowBrand {
void showMessage(String s ) ;
}
public class TV implements ShowBrand{
public void showMessage(String s) {
System.out.println(s);
}
}
public class PC implements ShowBrand{
public void showMessage(String s) { // 实现了接口方法
System.out.println(s);
}
public void play() { // 非接口方法
System.out.println("da");
}

}

2 接口回调的多态性

   由接口产生的多态性是指不同的类在实现同一个接口时可能具有不同的结果 ,接口声明的对象在回调接口方法时就具有多种形态. 

public static void main(String[] args) {
ComputeAverage computer ;
computer = new MusicScore() ;
double result = computer.average(10,9.89,9.67,8.9,9.77) ;
System.out.println("最后得分 :"+result);
computer = new SchoolScore() ;
result = computer.average(89,96,98,66,78,69,78) ;
System.out.println("班级平均成绩: " +result);

}

接口: 

public interface ComputeAverage {
double average(double ...x) ;
}
public class MusicScore implements ComputeAverage{
public double average(double ...x) {
int count = x.length ;
double aver = 0 ,temp = 0 ;
for(int i = 0 ; i<count ; i++ ) {
for(int j = i ; j<count ; j++) {
if(x[j]>x[i]) {
temp = x[j] ;
x[j] = x[i] ;
x[i] =temp ;
}
}
}

for(int i = 1 ;i<count-1 ; i++) {
aver +=x[i] ;
}
if(count>2) {
aver = aver/(count-2) ;
}
else {
aver =0 ;
}
return aver ;
}
}

 

public class SchoolScore implements ComputeAverage{
public double average(double ...x) {
int count = x.length ;
double aver = 0 ;
for(double param:x ) {
aver +=param ;
}
return aver/count ;
}
}