接口回调

[size=medium][color=red]关于接口回调[/color][/size]
[color=red]接口回调实多态的另一种体现。接口回调是指:可以把使用某一接口的类创建的对象的引用赋给该接口声明的接口变量中,那么该接口变量就可以调用被类实现的接口中的方法,当接口变量调用被类实现的接口中的方法时,就是通知相应的对象调用接口的方法,称为接口回调。不同的类在使用同一接口时,可能具有不同的功能体现,即接口的方法体不必相同,因此接口回调可能产生不同的行为。[/color]
下面是简单的接口回调:
package com.demo;

public class Demo1 {

public static float getSquare(Square s) {
return s.getSquare() ;
}

public static void main(String[] args) {
Rectangle r = new Rectangle(3, 4) ;
Circle c = new Circle(2) ;

float f1 = getSquare(r) ;
float f2 = getSquare(c) ;

System.out.println("长方形的面积:"+f1) ;
System.out.println("圆形的面积:"+f2) ;
}
}

interface Square {
static final float PI = 3.14f ;
public float getSquare() ;
}

class Rectangle implements Square {
int height ;
int length ;

Rectangle(int height, int length) {
this.height = height ;
this.length = length ;
}
@Override
public float getSquare() {

return (height*length);
}
}
class Circle implements Square {
int r ;

Circle(int r) {
this.r = r ;
}

@Override
public float getSquare() {
return PI*r*r ;
}
}


实际上用下面的代码也可以实现这样的功能,只不过是用类来实现的,并不是接口
原则上用接口会方便些!
package com.demo;

public class Demo2 {

public static float getSquare(Square s) {
return s.getSquare() ;
}

public static void main(String[] args) {
Rectangle r = new Rectangle(3, 4) ;
Circle c = new Circle(2) ;

float f1 = getSquare(r) ;
float f2 = getSquare(c) ;

System.out.println("长方形的面积:"+f1) ;
System.out.println("圆形的面积:"+f2) ;
}
}

class Square {
static final float PI = 3.14f ;
public float getSquare() {
return 0 ;
}
}

class Rectangle extends Square {
int height ;
int length ;

Rectangle(int height, int length) {
this.height = height ;
this.length = length ;
}
@Override
public float getSquare() {

return (height*length);
}
}
class Circle extends Square {
int r ;

Circle(int r) {
this.r = r ;
}

@Override
public float getSquare() {
return PI*r*r ;
}
}


两个程序只是稍微一点点不一样,下面的这个是多态的方式。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值