考虑以下代码:
import java.io.*;
import java.util.*;
class parent{
private static int static_count;
final void static_display(){
for(int i=0; i< 1000000; i++){
Object obj = new Object();
}
System.out.println("Static method called"+static_count+"times");
}
public void dynamic_display(){
System.out.println("implemented in child");
}
}
class child extends parent{
private static int dynamic_count;
public void dynamic_display(){
for(int i=0; i< 1000000; i++){
Object obj = new Object();
}
System.out.println("dynamic method called"+dynamic_count+"times");
}
}
class sample{
public static void main(String args[]){
parent pnt= new parent();
parent pnt2=new child();
//static binding
long startTime = System.nanoTime();
pnt.static_display();
long elapsedTime = System.nanoTime() - startTime;
System.out.println("Total execution time for static binding in millis: "
+ elapsedTime/1000000);
//dynamic binding
long startTime2 = System.nanoTime();
pnt2.dynamic_display();
long elapsedTime2 = System.nanoTime() - startTime2;
System.out.println("Total execution time for dynamic binding in millis: "
+ elapsedTime2/1000000);
}
}
执行此代码时,我得到以下答案,
Static method called0times
Total execution time for static binding in millis: 11
dynamic method called0times
Total execution time for dynamic binding in millis: 9
只考虑结果中的执行时间。我试图找到执行静态和动态绑定方法所花费的时间。但是根据我的回答,动态绑定比静态绑定要快。这怎么可能。我在任何地方都错了。