接口對象的實例化在接口回調中的使用


 

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

接口回調:可以把實現某一接口類創建的對象的引用賦給該接口聲明的接口變量,那么該 
接口變量就可以調用被類實現的接口中的方法。實際上,當接口變量調用被類實現的接口 
中的方法時,就是通知相應的對象調用接口方法。 
我們看下面的例子:

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM