zoukankan      html  css  js  c++  java
  • 接口的上溯造型——《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 ///:~

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

  • 相关阅读:
    python分布式进程
    python协程
    python线程同步
    Linux内核-链表
    java基础-003
    java基础-002
    JVM-class文件完全解析-魔数
    JVM-JDK命令行工具
    JVM-类文件结构
    Linux内核-模块编译和安装
  • 原文地址:https://www.cnblogs.com/skyfffire/p/6488769.html
Copyright © 2011-2022 走看看