• 接口的上溯造型——《Thinking in Java》随笔015


     1 //: Adventure.java
     2 package cn.skyfffire;
     3 
     4 /**
     5  * 
     6  * @author skyfffire
     7  *
     8  * 此类用于研究接口的上溯造型
     9  */
    10 interface CanFight {
    11     void fight();
    12 }
    13 
    14 interface CanSwim {
    15     void swim();
    16 }
    17 
    18 interface CanFly {
    19     void fly();
    20 }
    21 
    22 class ActionCharacter {
    23     public void fight() {}
    24 }
    25 
    26 class Hero extends ActionCharacter 
    27     implements CanFight, CanSwim, CanFly {
    28     
    29     @Override
    30     public void fight() {
    31         System.out.println("fight function run.");
    32     }
    33     
    34     @Override
    35     public void swim() {
    36         System.out.println("swim function run.");
    37     }
    38     
    39     @Override
    40     public void fly() {
    41         System.out.println("fly function run.");
    42     }
    43 }
    44 
    45 public class Adventure {
    46     static void t(CanFight x) {
    47         x.fight();
    48     }
    49     
    50     static void u(CanSwim x) {
    51         x.swim();
    52     }
    53     
    54     static void v(CanFly x) {
    55         x.fly();
    56     }
    57     
    58     static void w(ActionCharacter x) {
    59         x.fight();
    60     }
    61     
    62     public static void main(String[] args) {
    63         Hero i = new Hero();
    64         
    65         t(i);
    66         u(i);
    67         v(i);
    68         w(i);
    69     }
    70 }
    71 
    72 ///:~

    可以发现,类/抽象类/接口 都可以进行上溯造型,而且实现多个接口的类可以对任意一个接口进行上溯造型

  • 相关阅读:
    lab anycast rp
    激光 & 激光器
    管道机器人结构设计及控制系统搭建
    自动开关灯装置
    基于MATLAB步态算法仿真的六足仿生机器人
    蓝牙AT模式
    语音识别LD3320
    蓝牙模块设置
    6红外遥控程序
    62、如何消除碎片文件
  • 原文地址:https://www.cnblogs.com/skyfffire/p/6488769.html
Copyright © 2020-2023  润新知