| | 85 | |
| | 86 | == 範例 == |
| | 87 | |
| | 88 | {{{ |
| | 89 | #!java |
| | 90 | interface CanFight { |
| | 91 | void fight(); |
| | 92 | } |
| | 93 | |
| | 94 | interface CanSwim { |
| | 95 | void swim(); |
| | 96 | } |
| | 97 | |
| | 98 | interface CanFly { |
| | 99 | void fly(); |
| | 100 | } |
| | 101 | |
| | 102 | interface CanClimb { |
| | 103 | void climb(); |
| | 104 | } |
| | 105 | |
| | 106 | class ActionCharacter { |
| | 107 | public void fight() {} |
| | 108 | } |
| | 109 | |
| | 110 | class Hero extends ActionCharacter |
| | 111 | implements CanFight, CanSwim, CanFly, CanClimb { |
| | 112 | public void swim() {} |
| | 113 | public void fly() {} |
| | 114 | public void climb() {} |
| | 115 | } |
| | 116 | |
| | 117 | public class Ex09 { |
| | 118 | static void t(CanFight x) { |
| | 119 | x.fight(); |
| | 120 | } |
| | 121 | static void u(CanSwim x) { |
| | 122 | x.swim(); |
| | 123 | } |
| | 124 | static void v(CanFly x) { |
| | 125 | x.fly(); |
| | 126 | } |
| | 127 | static void z(CanClimb x) { |
| | 128 | x.climb(); |
| | 129 | } |
| | 130 | static void w(ActionCharacter x) { |
| | 131 | x.fight(); |
| | 132 | } |
| | 133 | public static void main(String[] args) { |
| | 134 | Hero h = new Hero(); |
| | 135 | t(h); // Treat it as a CanFight |
| | 136 | u(h); // Treat it as a CanSwim |
| | 137 | v(h); // Treat it as a CanFly |
| | 138 | z(h); // Treat it as a CanClimb |
| | 139 | w(h); // Treat it as an ActionCharacter |
| | 140 | } |
| | 141 | } |
| | 142 | }}} |