1. Java 中允许派生类中引入基类的重载方法
例如:
1 package JavaProject; 2 class A{ 3 public void display(){System.out.println("null");} 4 public void display(int i){System.out.println(""+i);} 5 } 6 public class B extends A{ 7 public void display(char a){System.out.println(a);} 8 public static void main(String[]args) 9 { 10 B b=new B(); 11 b.display('a'); 12 b.display(); 13 b.display(10); 14 15 A a=b; 16 a.display('a');//out:97,调用的是display(int) 17 a.display();//ok 18 a.display(10);//ok 19 } 20 }
如果要覆盖基类中的方法,可以用@Override 注解,这样可以避免不小心重载
2.C++中不允许派生类中引入基类的重载方法,与基类方法名相同时会屏蔽掉基类中所有的该方法的重载
1 #include<iostream> 2 using namespace std; 3 class A { 4 public: 5 void display() { cout << "null" << endl; } 6 void display(int i) { cout << i << endl; } 7 }; 8 class B :public A{ 9 public: 10 void display(char i) { cout << i << endl; } 11 }; 12 int main() 13 { 14 B b = B(); 15 b.display('a'); 16 //b.display();//error C++中要完成在派生类中覆盖基类的方法,就会屏蔽掉基类中重载的所有方法 17 18 A a = b; 19 a.display();//null 20 a.display(10);//out:10 21 a.display('a');//out:97 调用的是dispaly(int)。 22 return 0; 23 }
3.Java与C++中的继承关系中多态的体现
Java中:
1 package JavaProject; 2 class A{ 3 public void display(int i){System.out.println(i);} 4 } 5 public class B extends A{ 6 public void display(int a){System.out.println(a+10);} 7 public static void main(String[]args) 8 { 9 A a=new B(); 10 a.display(10);//20 11 } 12 }
Java 中没有相对C++而言没有虚函数和指针,所以当派生类中方法名、参数列表与基类中的一样时,发生的是覆盖,而没有隐藏的用法
C++中:
1 #include<iostream> 2 using namespace std; 3 class A { 4 public: 5 virtual void display(int i) { cout << i << endl; } 6 }; 7 class B :public A{ 8 public: 9 virtual void display(int i) { cout << i + 10<< endl; } 10 }; 11 int main() 12 { 13 A * a = new B(); 14 a->display(10); 15 /* 16 A a=B(); 17 a.display();//10 隐藏用法 18 */ 19 20 return 0; 21 }
C++中发生覆盖必须满足三个条件:(1)使用虚函数 (2)方法名相同 (3)参数列表相同