JAVA中多态与C++多态的区别

原文出自:http://blog.csdn.net/hihui/article/details/8604779

  1. #include <stdio.h>  
  2.   
  3. class Base  
  4. {  
  5. public:  
  6.     int i;  
  7.   
  8.     Base()  
  9.     {  
  10.         i = 99;  
  11.         amethod();  
  12.     }  
  13.   
  14.     virtual void amethod()  
  15.     {  
  16.         printf("Base.amethod() ");  
  17.     }  
  18.   
  19. };  
  20.   
  21. class Derived : public Base  
  22. {  
  23. public:  
  24.     int i;  
  25.   
  26.     Derived() {  
  27.         i = -1;  
  28.     }  
  29.   
  30.     virtual void amethod()  
  31.     {  
  32.         printf("Derived.amethod() ");  
  33.     }  
  34.   
  35. };  
  36.   
  37. int main(int argc, char *argv[])  
  38. {  
  39.     Base *b = new Derived();  
  40.     printf("%d ",b->i);  
  41.     b->amethod();  
  42. }  




其输出结果为:

Base.amethod()
99
Derived.amethod()

同样的java代码

[java] view plaincopy
 
  1. class Base  
  2. {  
  3.     int i = 99;  
  4.   
  5.     public void amethod()  
  6.     {  
  7.         System.out.println("Base.amethod()");  
  8.     }  
  9.   
  10.     Base()  
  11.     {  
  12.         amethod();  
  13.     }  
  14. }  
  15.   
  16. class Derived extends Base  
  17. {  
  18.     int i = -1;  
  19.   
  20.     public void amethod()  
  21.     {  
  22.         System.out.println("Derived.amethod()");  
  23.     }  
  24.   
  25.     public static void main(String argv[])  
  26.     {  
  27.         Base b = new Derived();  
  28.         System.out.println(b.i);  
  29.         b.amethod();  
  30.     }  
  31. }  


其输出结果为

Derived.amethod()
99
Derived.amethod()

差异体现在第一行输出;

这行是在Derived的构造函数中输出的,Derived本身没有构造函数,它只调用父类的构造函数,即Base的amethod();

对于C++代码,执行的是Base::amethod(); 

对于Java代码,执行的是Derived::amthod();

为什么呢,在C++中调用基类的amethod时,此时子类还没有准备好,故执行的是基类的amethod.

原文地址:https://www.cnblogs.com/coding-of-love/p/4045727.html