• Java学习-多态


     

     结合接口(interface)一起理解:

    目录结构如下:

     ADAPHero类

    1 package charactor;
    2 import property.Mortal;
    3 public class ADAPHero extends Hero implements Mortal {
    4     
    5     public  void die()
    6     {
    7         System.out.println("ADAPHero died");
    8     }
    9 }

    ADHero类

     1 package charactor;
     2 import property.Mortal;
     3 public class ADHero extends Hero implements Mortal
     4 {
     5     public void die()
     6     {
     7         System.out.println("ADHero died");
     8     }
     9 
    10 }

    APHero类

    1 package charactor;
    2 import property.Mortal;
    3 public class APHero extends Hero implements Mortal{
    4     public  void die()
    5     {
    6         System.out.println("APHero died");
    7     }
    8 }

    Mortal接口类

    1 package property;
    2 
    3 public interface Mortal {
    4     public  void die();
    5 }

    关键的Hero类:

     1 package charactor;
     2 import property.Mortal;
     3 public class Hero {
     4     public String name;
     5     protected float hp;
     6  
     7     public void kill(Mortal m)
     8     {
     9         m.die();
    10     }
    11  
    12     public static void main(String[] args) {
    13          
    14       Hero h1=new Hero();
    15       h1.name="garen";
    16       ADHero ad=new ADHero();
    17       APHero ap=new APHero();
    18       ADAPHero adap=new ADAPHero();
    19       h1.kill(ad);  //传参时:Mortal m = ad,父类接口Mortal的引用m指向子类对象ad,以下同理
    20       h1.kill(ap);
    21       h1.kill(adap);
    22       //同样的Hero类型,同样的kill方法,不同的效果
    23     }
    24        
    25 }

    Hero类的主方法运行结果:

    ADHero died
    APHero died
    ADAPHero died

     

  • 相关阅读:
    获得客户端的信息
    JavaScript--垃圾回收器
    JavaScript--函数-按值传递
    JavaScript--声明提前
    JavaScript--函数-01
    JavaScript--赋值表达式(typeof-delete-void)
    JavaScript—赋值表达式-1
    JavaScript--机选双色球
    正则表达式的预判
    自定义比较器函数
  • 原文地址:https://www.cnblogs.com/gilgamesh-hjb/p/12133642.html
Copyright © 2020-2023  润新知