一、向上转型
下面一句话出自Thinking in Java。
使用接口的核心原因:为了能够向上转型为多个基类型。即利用接口的多实现,可向上转型为多个接口基类型。
j ava接口或抽象类都可以使用向上转型,它们用的都是java运行时多态技术,或者叫运行期绑定技术。
下面是一个java接口的普遍用法,
interface People{
void peopleList();
}
class Student implements People{
public void peopleList(){
System.out.println("I’m a student.");
}
}
class Teacher implements People{
public void peopleList(){
System.out.println("I’m a teacher.");
}
}
public class Example{
public static void main(String args[]){
People a; //声明接口变量
a=new Student(); //实例化,接口变量中存放对象的引用
a.peopleList(); //接口回调
a=new Teacher(); //实例化,接口变量中存放对象的引用
a.peopleList(); //接口回调
}
}
结果:
I’m a student.
I’m a teacher.
public static void testMethod(){
for(int i=0; i<100000000; i++){
}
}
public void testTime(){
long begin = System.currentTimeMillis();//测试起始时间
testMethod();//测试方法
long end = System.currentTimeMillis();//测试结束时间
System.out.println("[use time]:" + (end - begin));//打印使用时间
}
首先定一个回调接口:
public interface CallBack {
//执行回调操作的方法
void execute();
}
然后再写一个工具类:
public class Tools {
public void testTime(CallBack callBack) {
long begin = System.currentTimeMillis();//测试起始时间
callBack.execute();/// 进行回调操作
long end = System.currentTimeMillis();//测试结束时间
System.out.println("[use time]:" + (end - begin));//打印使用时间
}
public static void main(String[] args) {
Tools tool = new Tools();
tool.testTime(new CallBack(){
//定义execute方法
public void execute(){
//这里可以加放一个或多个要测试运行时间的方法
TestObject.testMethod();
}
});
}