接口对象的实例化在接口回调中的使用
首先澄清一个问题,就是接口不仅可以声明对象,而且可以把对象实例化!作用见下文。
接口回调:可以把实现某一接口类创建的对象的引用赋给该接口声明的接口变量,那么该
接口变量就可以调用被类实现的接口中的方法。实际上,当接口变量调用被类实现的接口
中的方法时,就是通知相应的对象调用接口方法。
我们看下面的例子:
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中是不允许的。
- 2016年6月22日
- lvs之fullnat与pacemaker的构建
- Linux下iptables屏蔽IP和端口号
- Kali linux 安装RTL8192eu 驱动
- C#中System.Func<>与System.Action<>的区别
- 读后摘要:RISC和CISC的效能之争
- 记录Mybatis和Ehcache结合时启用延迟加载的一个坑
- git使用攻略
- 获取memcache缓存下所有的键值对信息
- 睡眠猴子——beta阶段项目总结
- Git具体问题:如何安全的push文件到工作分支
- C/C++内存管理机制
- MIS性能优化常见问题与方案(辅助项目组性能优化的总结贴)
- mybatis二级缓存应用及与ehcache整合
- 优先级反转
- KMP算法详解
- 中断驱动的自行车码表
- Cortex指令集相比ARM的优势
- [Java] Java 技术和 JVM 基础
- Activity以singleTask模式启动,intent传值的解决办法