黑马程序员技术交流社区

标题: 多态 [打印本页]

作者: longyun    时间: 2016-5-31 21:29
标题: 多态
多态怎么应用啊?哪位大神给举个例子啊?
作者: 元笙    时间: 2016-5-31 22:59
多态,最常用的场合就是当做参数进行传递,可以提高代码的扩展性,给你举个例子
假设,有一个方法的形参是一个类类型变量,在方法体中,使用这个传入的对象引用调用方法eat()
  1. class DemoMul  {
  2.         public static void main(String[] args)  {
  3.                 //如果不使用多态,调用Dog和Cat类的方法就必须写如下好多eatMathod(),重载
  4.                 eatMethod(new Dog());
  5.                 eatMethod(new Cat());
  6.                 //...
  7.                 //如果有n个,不是要写n个eatMathod()
  8.                 /*使用多态,则只有写一个eatMathod()即可*/
  9.                 eatMethod(new Dog());
  10.                 eatMethod(new Cat());
  11.         }
  12.         public static void eatMethod(Dog d){
  13.                 d.eat();
  14.         }
  15.         public static void eatMethod(Cat c){
  16.                 c.eat();
  17.         }
  18.         //...
  19.         /*使用多态,则只有写一个eatMathod()即可*/
  20.         public static void eatMethod(Animal a){
  21.                 a.eat();
  22.         }
  23. }
  24. abstract class Animal {
  25.         public abstract void eat();
  26. }

  27. class Cat extends Animal {
  28.         //重写父类抽象方法
  29.         public void eat(){
  30.                 System.out.println("猫吃鱼");
  31.         }
  32. }

  33. class  Dog extends Animal {
  34.         public void eat(){
  35.                 System.out.println("狗吃骨头");
  36.         }
  37. }
复制代码





欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2