[size=medium][color=red]关于接口回调[/color][/size]
[color=red]接口回调实多态的另一种体现。接口回调是指:可以把使用某一接口的类创建的对象的引用赋给该接口声明的接口变量中,那么该接口变量就可以调用被类实现的接口中的方法,当接口变量调用被类实现的接口中的方法时,就是通知相应的对象调用接口的方法,称为接口回调。不同的类在使用同一接口时,可能具有不同的功能体现,即接口的方法体不必相同,因此接口回调可能产生不同的行为。[/color]
下面是简单的接口回调:
实际上用下面的代码也可以实现这样的功能,只不过是用类来实现的,并不是接口
原则上用接口会方便些!
两个程序只是稍微一点点不一样,下面的这个是多态的方式。
[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 ;
}
}
两个程序只是稍微一点点不一样,下面的这个是多态的方式。