java中多态的例子
人气:0通过例子来理解java多态!
操作方法
- 01
abstract class Animal{abstract void eat();}class Pig extends Animal{public void eat(){System.out.println("饲料");}public static void sleep(){System.out.println("睡觉");}}class Dog extends Animal{public void eat(){System.out.println("骨头");}public static void Pao(){System.out.println("跑");}}class Cat extends Animal{public void eat(){System.out.println("吃鱼");}public static void cachmouth(){System.out.println("抓老鼠");}}
- 02
class test{public static void main(String[] ats)public static void eatfunction(Animal a){a.eat();if(a instanceof Cat){Cat c=(Cat)a;c.cachmouth();}else if(a instanceof Dog){Dog d =(Dog)a;d.Pao();}else if(a instanceof Pig){Pig p =(Pig)a;p.sleep();}}}
- 03
多态的好处是大大提高了函数的扩展性!
特别提示
必须是类与类之间要有关系!
存在覆盖!
加载全部内容