A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

© linder_qzy 中级黑马   /  2015-3-9 22:08  /  509 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 linder_qzy 于 2015-3-9 22:09 编辑

多态是什么
事物存在的多种体现形态
多态的表现形式
父类的引用指向了自己子类的对象;父类的引用也可以接收自己的子类对象
多态的好处
大大提高了代码的扩展性。
多态的前提
类与类之间必须有关系,要那么继承,要么实现;方法需要完全覆盖。
多态的弊端
提高了扩展性,但是只能用父类的引用去访问父类的成员。
  1. abstract class Animal  
  2. {  
  3.     public abstract void eat();  
  4. }  
  5. class Cat extends Animal  
  6. {  
  7.     public void eat(){  
  8.         System.out.println("吃鱼");  
  9.     }  
  10.     public void catchMouse(){  
  11.         System.out.println("抓老鼠");  
  12.     }  
  13. }  
  14. class Dog extends Animal  
  15. {  
  16.     public void eat(){  
  17.         System.out.println("吃骨头");  
  18.     }  
  19.     public void catchHome(){  
  20.         System.out.println("看家");  
  21.     }  
  22. }  
  23. class Demo01_DuoTai  
  24. {  
  25.     public static void main(String[] args)   
  26.     {  
  27.         //多态的表现形式:父类的引用指向了自己子类的对象;父类的引用也可以接收自己的子类对象  
  28.         function(new Cat());  
  29.         function(new Dog());  
  30.         function(new Pig());  
  31.         /*
  32.         输出结果
  33.         吃鱼
  34.         吃骨头
  35.         */  
  36.     }  
  37.     public static void function(Animal a){  
  38.         a.eat();  
  39.     }  
  40. }  
复制代码


介绍一个关键字 instanceof
instanceof 运算符是用来在运行时指出对象是否是特定类的一个实例。instanceof通过返回一个布尔值来指出,这个对象是否是这个特定类或者是它的子类的一个实例
  1. abstract class Ainimal {  
  2.       
  3.     abstract void eat();  
  4. }  
  5. class Cat extends Ainimal{  
  6.     public void eat()  
  7.     {  
  8.         System.out.println("猫吃鱼!!");  
  9.     }  
  10.     public void catchMouse()  
  11.     {  
  12.         System.out.println("猫抓老鼠!!");  
  13.     }  
  14. }  
  15. class Dog extends Ainimal{  
  16.     public void eat()  
  17.     {  
  18.         System.out.println("狗吃肉!!");  
  19.     }  
  20.     public void catchHome()  
  21.     {  
  22.         System.out.println("狗看家!!");  
  23.     }  
  24. }  
  25. public class Demo0309  
  26. {  
  27.     public static void main(String[] args)  
  28.     {  
  29.         function(new Cat());  
  30.         function(new Dog());  
  31.     }  
  32.     public static void function(Ainimal a)  
  33.     {  
  34.         a.eat();  
  35.         //判断a是否是Cat的实例  
  36.         if(a instanceof Cat)  
  37.         {  
  38.             Cat c = (Cat)a;  
  39.             c.catchMouse();  
  40.         }  
  41.         if(a instanceof Dog)  
  42.         {  
  43.             Dog d = (Dog)a;  
  44.             d.catchHome();  
  45.         }  
  46.     }  
  47. }  
  48. /*
  49. * 输出结果
  50. * 猫吃鱼!!
  51.    猫抓老鼠!!
  52.    狗吃肉!!
  53.    狗看家!!
  54. */  
复制代码

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马