Understanding polymorphism, overloading, and rewriting

typical example:

[html]  view plain copy  
  1. public class Alpha {  
  2.     public void foo(String... args){  
  3.         System.out.println("Alpha:foo");  
  4.     }  
  5.        
  6.     public void bar(String a){  
  7.         System.out.println("Alpha:bar");  
  8.     }  
  9. }  
  10. public class Beta extends Alpha {  
  11.        
  12.     public void foo(String a){ //The same as the method name of the parent class, the parameters are different, here is the overload  
  13.         System.out.println("Beta:foo");  
  14.     }  
  15.        
  16.     public void bar(String a){ //The same as the method name of the parent class, the parameter list is also the same, there is an inheritance relationship, here is the rewrite  
  17.         System.out.println("Beta:bar");  
  18.     }  
  19.     public static void main(String[] args) {  
  20.         // TODO Auto-generated method stub  
  21.         Alpha  a  =  new  Beta(); //parent class  xx  =  new  subclass()  
  22.         Beta  b  = (Beta)a; //Subclass  xx  =  new  subclass()  
  23.         a.foo("test");  
  24.         b.foo("test");  
  25.         a.bar("test");  
  26.         b.bar("test");  
  27.            
  28.     }  
  29.    
  30. }  
Output result:

[html]
  view plain copy  
  1. 1>  
  2. Alpha:foo  
  3. Beta:foo  
  4. 2>  
  5. Beta: bar  
  6. Beta: bar  

Result analysis:

1> The foo methods of the parent class and the child class are different because their parameters are different. So there is no polymorphism. If you call foo with the reference of the parent class, then the foo(String ... args) of the parent class is called. method, args is a variable parameter, handled as an array. When you call foo with a reference to a subclass, the subclass's foo(String a) method is called.

2> The bar() method, the parent class and the child class are the same, so using polymorphism, whether the parent class reference or the child class reference is used, the bar() of the child class is called.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324730075&siteId=291194637