多态,指某一样事物的多样性。

在java中,多态的前提是:

      1 有继承或者实现关系

      2  有方法的重写  

多态的好处:提高程序扩展性,对于某一类有共同特性的对象,我们可以抽象出他们的父类,通过操作父类来指挥一堆对象做事情。

多态的体现:把一个子类对象当做一个父类对象来看,或者说父类引用指向之类对象。即Person p  = new Student();这种形式。

多态的缺陷:访问的局限性,比如上例中p只能访问Person类中的方法,不能访问Student类中的方法。

多态最基本两个定理:

定理一  当我们把一个子类对象当做父类对象来看时,比如Person p = new Student();只能访问父类中的方法,不能访问子类中的方法:

例如,定义父子类Person Student如下:


  
  1. package com.anjoyo.demo;  
  2.  
  3. public class Person {  
  4.     private String name;  
  5.     private int age;  
  6.       
  7.     public Person() {  
  8.     }  
  9.     public Person(String name, int age) {  
  10.         this.name = name;  
  11.         this.age = age;  
  12.     }  
  13.     public void move(){  
  14.         System.out.println("Person move !");  
  15.     }  
  16. }  

定义Student类,Student继承自Person


  
  1. package com.anjoyo.demo;  
  2.  
  3. public class Student extends Person{  
  4.     public void study(){  
  5.         System.out.println("learn");  
  6.     }  
  7. }  

测试类代码如下:


  
  1. package com.anjoyo.demo;  
  2.  
  3. public class TestStudent {  
  4.     public static void main(String[] args) {  
  5.         Person p =new Student();  
  6.         p.move();  
  7.         //p.study();    
  8.         //报语法错误:The method study() is undefined for the type Person  
  9.     }  
  10. }  

可以看出p对象不能调用子类Student的方法study()。

定理二  当我们把一个子类对象当做父类对象来看时,比如Person p = new Student();如果在子类中重写(覆盖)了父类中的方法,在调用该方法时,调用的是子类的方法。

比如在Student类中重写move方法,如下:


  
  1. package com.anjoyo.demo;  
  2.  
  3. public class Student extends Person{  
  4.     public void study(){  
  5.         System.out.println("learn");  
  6.     }  
  7.     public void move(){  
  8.         System.out.println("Student running !");  
  9.     }  
  10. }  

在测试类中用p再调用move()方法时,输出的是Student running !


  
  1. package com.anjoyo.demo;  
  2.  
  3. public class TestStudent {  
  4.     public static void main(String[] args) {  
  5.         Person p =new Student();  
  6.         p.move();//Student running !  
  7.     }  
  8. }