java(二十四)【面向对象】多态

多态:某一类事物的多种存在形式

例:动物中的猫、狗

猫这个对象对象的类型是猫类型 猫 x = new 猫();

同时猫也是动物中的一种,也可以把猫称为动物

动物 y= new 猫();

动物是猫和狗具体事物中抽取出来的父类型,父类型引用指向了子类对象

 多态的体现

父类的引用指向了自己的子类对象

父亲的引用也可以接受自己的子类对象

多态的前提

  必须是类与类之间有关系,要么继承,要么实现

  存在覆盖

多态的好处:大大提高了程序的扩展性

多态的弊端:提高了扩展性,但是只能使用父类的引用访问父类中的成员

 1 abstract class Animal{
 2     abstract void eat();
 3 }
 4 class  Cat extends Animal{
 5     public void eat(){
 6         System.out.println("吃鱼");
 7     }
 8     public void catchMouse(){
 9         System.out.println("抓老鼠");
10     }
11 }
12 class Dog extends Animal{
13     public void eat(){
14         System.out.println("吃骨头");
15 }
16     public void Kanjia()
17     {
18         System.out.println("看家");
19     }
20 }
21 public class Single {
22     public static void main(String[] args) {
23         //Cat c=new Cat();
24         //function(c);
25         function(new Dog());
26         function(new Cat());
27         
28     }
29     public static void function(Animal a)
30     {
31         a.eat();
32     }
33     /*
34     public static void  function(Cat c) {
35         c.eat();
36     }
37     public static void  function(Dog c) {
38         c.eat();
39     }*/
40 }

 

运行结果:

   

 

posted @ 2015-09-14 14:43  花花妹子。  阅读(103)  评论(0)    收藏  举报