接口对象的实例化在接口回调中的使用

首先澄清一个问题,就是接口不只能够声明对象,并且能够把对象实例化!做用见下文。html

接口回调:能够把实现某一接口类建立的对象的引用赋给该接口声明的接口变量,那么该 
接口变量就能够调用被类实现的接口中的方法。实际上,当接口变量调用被类实现的接口 
中的方法时,就是通知相应的对象调用接口方法。 
咱们看下面的例子:java

 

interface Computerable{public double area();}
class Rec implements Computerable{
double a,b;
Rec(double a,double b){
this.a = a;
this.b = b;
}
public double area() {
return (a*b);
}
}
class Circle implements Computerable{
double r;
Circle(double r){
this.r = r;
}
public double area() {return (3.14*r*r);} 
}
class Volume {
Computerable bottom;
double h;
Volume(Computerable bottom, double h){
this.bottom = bottom;
this.h = h;
}
public void changeBottome(Computerable bottom){
this.bottom = bottom;
}
public double volume(){
return (this.bottom.area()*h/3.0);
}
}
public class InterfaceRecall {
public static void main(String[] args){
Volume v = null;
Computerable bottom = null;//借口变量中存放着对对象中实现了该接口的方法的引用
bottom = new Rec(3,6);
System.out.println("矩形的面积是:"+bottom.area());
v = new Volume(bottom, 10);//体积类实例的volum方法实际上计算的是矩形的体积,下同
System.out.println("棱柱的体积是:"+v.volume());
bottom = new Circle(5);
System.out.println("圆的面积是:"+bottom.area());
v.changeBottome(bottom);System.out.println("圆柱的体积是:"+v.volume());
}
}

 

输出: 
矩形的面积是:18.0 
棱柱的体积是:60.0 
圆的面积是:78.5 
圆柱的体积是:261.6666666666667函数


经过上面的例子,咱们不难看出,接口对象的实例化其实是一个接口对象做为一个引用 
,指向实现了它方法的那个类中的全部方法,这一点很是象C++中的函数指针,可是倒是有 
区别的。java中的接口对象实例化其实是一对多(若是Computerable还有其余方法,bo 
ttom仍然能够调用)的,而C++中的函数指针是一对一的。 
可是须要注意的是,接口对象的实例化必须用实现它的类来实例化,而不能用接口自己实 
例化。用接口自己实例化它本身的对象在Java中是不容许的。this

相关文章
相关标签/搜索