java多态的理解

面向对象语言中的类有三个特征,封装、继承、多态。封装与继承很好理解,那什么是多态呢?

1.什么是多态?

多态的定义:指允许不同类的对象对同一消息做出响应。即同一消息可以根据发送对象的不同而采用多种不同的行为方式。(发送消息就是函数调用)

简单点解释就是:父类对象的引用指向子类的对象的实例,这样父类在调用方法时可能产生不同的效果!

2.多态实例

 1 abstract class Animal
 2 {
 3     abstract void eat();
 4 }
 5 class Dog extends Animal
 6 {
 7     void eat()
 8     {
 9         System.out.println("狗吃肉!");
10     }
11 }
12 class Cat extends Animal
13 {
14     void eat()
15     {
16         System.out.println("猫吃鱼!");
17     }
18 }
19 
20 class DuoTaiDemo 
21 {
22     public static void main(String[] args) 
23     {
24         Animal al=null;    
25 
26         al=new Dog();    
27         al.eat();
28         
29         System.out.println("------------------------");
30         
31         al=new Cat();        
32         al.eat();
33     }
34 }

代码输出:

3. 多态的调用

有如下代码:

 1 class Fu
 2 {
 3     int num = 2;
 4     void show()
 5     {
 6         System.out.println("fu show run");
 7     }
 8 
 9 
10     static void method()
11     {
12         System.out.println("fu static method run");
13     }
14 }
15 class Zi extends Fu
16 {
17     int num = 8;
18     void show()
19     {
20         System.out.println("Zi show run");
21     }
22     static void method()
23     {
24         System.out.println("zi static method run");
25     }
26 }

3.1 多态中的成员变量调用

多态调用时,对于成员变量,无论是编译还是运行,结果只参考引用型变量所属的类中的成员变量。

简单说:编译和运行都看左边。

如下代码:

public static void main(String[] args) 
    {
        //演示成员变量。
        Fu f = new Zi();
        System.out.println(f.num);//2
        Zi z = (Zi)f;
        System.out.println(z.num);//8
    }

输出:

2
8

3.2 多态中的成员函数调用

多态调用时,对于成员函数,
编译时,参考引用型变量所属的类中是否有被调用的方法。有,编译通过,没有编译失败。
运行时,参考的是对象所属的类中是否有调用的方法。
简单说:编译看左边,运行看右边

public static void main(String[] args) 
    {
        //演示成员方法。
        
        Fu f = new Zi();
        f.show();
    }

输出:

Zi show run

3.3 多态中的成员函数调用

简单说:编译和运行都看左边。

public static void main(String[] args) 
    {
        //演示静态方法。
        Fu f = new Zi();
        f.method();
        Zi z = (Zi)f;
        z.method();

        //其实可以像下面这样调用
        //Fu.method();
        //Zi.method();
    }

输出:

fu static method run
zi static method run
原文地址:https://www.cnblogs.com/renjing/p/6208379.html