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...

     

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

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


  • 相关阅读:
    Cesium的类-Camera
    FTP文件操作之上传文件
    cnBlog 的windows live writer 客户端配置
    Windows 7 USB DVD Download Tool 制作的U盘无法启动安装Windows7 SP1
    存储过程中对于文本是两个单引号,而不是一个单引号或者一个双引号
    BackGroundWorker使用总结
    SQL中IN,NOT IN,EXISTS,NOT EXISTS的用法和差别
    T-SQL中default值的使用
    partial 的好处
    sql where 1=1和 0=1 的作用
  • 原文地址:https://www.cnblogs.com/steve-jiang/p/6790173.html
Copyright © 2011-2022 走看看