首先澄清一个问题,就是接口不仅可以声明对象,而且可以把对象实例化!作用见下文。

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

 

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中是不允许的。

posted on 2012-01-30 17:00  瓦里奥  阅读(6211)  评论(1编辑  收藏  举报