【接口可以实例化吗】接口对象的实例化在接口回调中的使用方法

更新时间:2021-06-28    来源:面向对象编程    手机版     字体:

【www.bbyears.com--面向对象编程】

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

接口回调:可以把实现某一接口类创建的对象的引用赋给该接口声明的接口变量,那么该

接口变量就可以调用被类实现的接口中的方法。实际上,当接口变量调用被类实现的接口

中的方法时,就是通知相应的对象调用接口方法。

我们看下面的例子:

 

 代码如下

interfaceComputerable

  

{

  

publicdoublearea();

  

}

  

  

  

classRecimplementsComputerable

  

{

  

doublea,b;

  

Rec(doublea,doubleb)

  

{

  

this.a = a;

  

this.b = b;

  

}

  

publicdoublearea() {

  

return(a*b);

  

}

  

}

  

  

  

classCircleimplementsComputerable

  

{

  

doubler;

  

Circle(doubler)

  

{

  

this.r = r;

  

}

  

publicdoublearea() {

  

return(3.14*r*r);

  

}

  

}

  

  

  

classVolume

  

{

  

Computerable bottom;

  

doubleh;

  

Volume(Computerable bottom,doubleh)

  

{

  

this.bottom = bottom;

  

this.h = h;

  

}

  

  

  

publicvoidchangeBottome(Computerable bottom)

  

{

  

this.bottom = bottom;

  

}

  

  

  

publicdoublevolume()

  

{

  

return(this.bottom.area()*h/3.0);

  

}

  

}

  

  

  

publicclassInterfaceRecall {

  

publicstaticvoidmain(String[] args)

  

{

  

Volume v =null;

  

Computerable bottom =null;

  

  

  

//借口变量中存放着对对象中实现了该接口的方法的引用

  

bottom =newRec(3,6);

  

System.out.println("矩形的面积是:"+bottom.area());

  

v =newVolume(bottom,10);

  

//体积类实例的volum方法实际上计算的是矩形的体积,下同

  

System.out.println("棱柱的体积是:"+v.volume());

  

  

  

bottom =newCircle(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还有其他方法,bottom仍然可以调用)的,而C++中的函数指针是一对一的。  但是需要注意的是,接口对象的实例化必须用实现它的类来实例化,而不能用接口本身实例化。用接口本身实例化它自己的对象在Java中是不允许的。

本文来源:http://www.bbyears.com/jsp/126537.html