zoukankan      html  css  js  c++  java
  • Java多态

     

     

     

    在Java中有两种类型的多态性:编译时多态性和运行时多态性。

    编译时多态性就是指函数的重载而已,实现方法是根据函数的名字不同来调用。

    运行时多态性或动态方法分派是一个过程,它对重写方法的调用在运行时体现而不是编译时(因为方法调用是由JVM不是编译器决定的,所以它被称为运行时多态性)。

    在此过程中,通过超类的引用变量调用重写的方法。 要调用的方法基于引用的对象。

     

     
     1 class Super{
     2     void run() {
     3         System.out.println("SuperClass  running");
     4     }
     5 }
     6 
     7 class Child extends Super{
     8     void run() {
     9         System.out.println("Child  running");
    10     }
    11 
    12     public static void main(String args[]) {
    13         Super s = new Child ();// upcasting - 向上转换
    14         s.run();
    15     }
    16 }

    执行上面代码得到以下结果 :

    Child  running
     1 class Animal {
     2     void eat() {
     3         System.out.println("eating...");
     4     }
     5 }
     6 
     7 class Dog extends Animal {
     8     void eat() {
     9         System.out.println("eating bread...");
    10     }
    11 }
    12 
    13 class Cat extends Animal {
    14     void eat() {
    15         System.out.println("eating rat...");
    16     }
    17 }
    18 
    19 class Lion extends Animal {
    20     void eat() {
    21         System.out.println("eating meat...");
    22     }
    23 }
    24 
    25 class TestPolymorphism {
    26     public static void main(String[] args) {
    27         Animal a;
    28         a = new Dog();
    29         a.eat();
    30         a = new Cat();
    31         a.eat();
    32         a = new Lion();
    33         a.eat();
    34     }
    35 }

     执行上面代码得到以下结果 :

    eating bread...
    eating rat...
    eating meat...

     

    上面示例中,都是有关方法被覆盖而不是数据成员,因此运行时多态性不能由数据成员实现。

    如果重写数据成员,类似的代码只会输出超类数据成员。
    多级继承中,覆盖方法也可以实现多态。


  • 相关阅读:
    获取路径的方式
    读取XML文件(XmlNode和XmlElement区别)
    jQuery 选择器大全
    JS中Null与Undefined的区别
    浅谈JS中的!=、== 、!==、===的用法和区别
    sql面试 查找每个班级的前5名学生(取分类数据的前几条数据)
    C#动态方法调用
    C# 匿名对象(匿名类型)、var、动态类型 dynamic——实用之:过滤类属性、字段实用dynamic
    前言2
    2019-1-17 前言 C#高级编程(第11版)
  • 原文地址:https://www.cnblogs.com/steve-jiang/p/6790173.html
Copyright © 2011-2022 走看看