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

接口回调:可以把实现某一接口类创建的对象的引用赋给该接口声明的接口变量,那么该
接口变量就可以调用被类实现的接口中的方法。实际上,当接口变量调用被类实现的接口
中的方法时,就是通知相应的对象调用接口方法。
我们看下面的例子:
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());
}
} 文章名称:怎么在接口回调中的使用接口对象的实例化-创新互联
文章路径:http://www.jxjierui.cn/article/ceggds.html


咨询
建站咨询
