欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

接口對象的實(shí)例化在接口回調(diào)中的使用方法

 更新時(shí)間:2017年02月23日 08:51:19   投稿:jingxian  
下面小編就為大家?guī)硪黄涌趯ο蟮膶?shí)例化在接口回調(diào)中的使用方法。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧

首先澄清一個(gè)問題,就是接口不僅可以聲明對象,而且可以把對象實(shí)例化!作用見下文。

接口回調(diào):可以把實(shí)現(xiàn)某一接口類創(chuàng)建的對象的引用賦給該接口聲明的接口變量,那么該

接口變量就可以調(diào)用被類實(shí)現(xiàn)的接口中的方法。實(shí)際上,當(dāng)接口變量調(diào)用被類實(shí)現(xiàn)的接口

中的方法時(shí),就是通知相應(yīng)的對象調(diào)用接口方法。

我們看下面的例子:

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; 
 
 
 
//借口變量中存放著對對象中實(shí)現(xiàn)了該接口的方法的引用 
 
bottom = new Rec(3,6); 
 
System.out.println("矩形的面積是:"+bottom.area()); 
 
v = new Volume(bottom, 10); 
 
//體積類實(shí)例的volum方法實(shí)際上計(jì)算的是矩形的體積,下同 
 
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

通過上面的例子,我們不難看出,接口對象的實(shí)例化實(shí)際上是一個(gè)接口對象作為一個(gè)引用 ,指向?qū)崿F(xiàn)了它方法的那個(gè)類中的所有方法,這一點(diǎn)非常象C++中的函數(shù)指針,但是卻是有區(qū)別的。java中的接口對象實(shí)例化實(shí)際上是一對多(如果Computerable還有其他方法,bottom仍然可以調(diào)用)的,而C++中的函數(shù)指針是一對一的。 但是需要注意的是,接口對象的實(shí)例化必須用實(shí)現(xiàn)它的類來實(shí)例化,而不能用接口本身實(shí)例化。用接口本身實(shí)例化它自己的對象在Java中是不允許的。

以上這篇接口對象的實(shí)例化在接口回調(diào)中的使用方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論