怎么在接口回调中的使用接口对象的实例化

发布时间:2020-11-24 15:21:48 作者:Leah
来源:亿速云 阅读:110

本篇文章为大家展示了怎么在接口回调中的使用接口对象的实例化,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

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

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

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

我们看下面的例子:

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

上述内容就是怎么在接口回调中的使用接口对象的实例化,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。

推荐阅读:
  1. java中的接口能够被实例化吗
  2. 深入了解Java接口回调机制

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

接口 对象 实例化

上一篇:Android6.0应用中无法扫描蓝牙设备怎么办

下一篇:Android开发中怎么实现一个图片下载功能

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》