Poly.java |
1 | public class Poly { |
2 | |
3 | // An enum is just a set of possible values |
4 | public enum AttackType { |
5 | HEAT, EDGE, BLUNT, COLD, ACID, PUNCTURE |
6 | } |
7 | |
8 | // This is an example of a static inner class |
9 | public static class Attack { |
10 | public final String name; |
11 | public final AttackType type; |
12 | public final int damage; |
13 | public Attack(String name,AttackType type,int damage) { |
14 | this.name = name; |
15 | this.type = type; |
16 | this.damage = damage; |
17 | } |
18 | } |
19 | |
20 | // This is an example of an interface |
21 | public interface Monster { |
22 | public Attack getAttack(); |
23 | public void takeDamage(Attack a); |
24 | } |
25 | |
26 | // Orcs don't have an intrinsic attack, they |
27 | // have to carry a weapon. |
28 | public static class Orc implements Monster { |
29 | Attack weapon; |
30 | int life=20; |
31 | |
32 | public void setWeapon(Attack weapon) { |
33 | this.weapon = weapon; |
34 | } |
35 | @Override |
36 | public Attack getAttack() { |
37 | return weapon; |
38 | } |
39 | |
40 | @Override |
41 | public void takeDamage(Attack a) { |
42 | life -= a.damage; |
43 | if(life <=0 ) |
44 | System.out.println("dead"); |
45 | } |
46 | } |
47 | |
48 | public static class Dragon implements Monster { |
49 | final Attack breath = new Attack("Breath",AttackType.HEAT,50); |
50 | int life = 100; |
51 | |
52 | @Override |
53 | public Attack getAttack() { return breath; } |
54 | |
55 | @Override |
56 | public void takeDamage(Attack a) { |
57 | if(a.type == AttackType.COLD) |
58 | life -= a.damage; |
59 | else |
60 | System.out.println("No damage, ha, ha, ha"); |
61 | if(life <=0 ) |
62 | System.out.println("dead"); |
63 | } |
64 | } |
65 | |
66 | // Polymorphism in action |
67 | public static void attack(Monster attacker,Monster defender) { |
68 | defender.takeDamage(attacker.getAttack()); |
69 | } |
70 | |
71 | public static void main(String[] args) { |
72 | Orc orc = new Orc(); |
73 | Dragon dragon = new Dragon(); |
74 | orc.setWeapon(new Attack("Sword",AttackType.EDGE,10)); |
75 | attack(orc,dragon); |
76 | attack(dragon,orc); |
77 | } |
78 | } |
$ javac Poly.java
|
$ java Poly
No damage, ha, ha, ha
dead
|