typical example:
- public class Alpha {
- public void foo(String... args){
- System.out.println("Alpha:foo");
- }
- public void bar(String a){
- System.out.println("Alpha:bar");
- }
- }
- public class Beta extends Alpha {
- public void foo(String a){ //The same as the method name of the parent class, the parameters are different, here is the overload
- System.out.println("Beta:foo");
- }
- 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
- System.out.println("Beta:bar");
- }
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- Alpha a = new Beta(); //parent class xx = new subclass()
- Beta b = (Beta)a; //Subclass xx = new subclass()
- a.foo("test");
- b.foo("test");
- a.bar("test");
- b.bar("test");
- }
- }
- 1>
- Alpha:foo
- Beta:foo
- 2>
- Beta: bar
- 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.