User Tools

Site Tools


at-m42:lecture7

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
at-m42:lecture7 [2009/04/13 15:50] eechrisat-m42:lecture7 [2011/01/14 12:45] (current) – external edit 127.0.0.1
Line 745: Line 745:
  
 <code groovy> <code groovy>
-interface portable { +interface Portable 
- +    Boolean abstract canCarry(Player player) 
-    Boolean abstract canCarry(Player player)  // deferred method +
 } }
  
-abstract class AbstractItem implements portable {+abstract class AbstractItem implements Portable ... }
  
-    String toString()  // redefinition +class WeightyItem extends AbstractItem { ... }
-        return "Item: ${name} has value ${value}" +
-    } +
-     +
-    Boolean hasDescription() { +
-        return ! (description == ''+
-    } +
-     +
-    Boolean canCarry(Player player)  { // redefinition +
-    return (player.funds >= value) +
-    }+
  
-// ----- properties ----------------------------------+class MagicalItem extends AbstractItem { ... } 
 +</code>
  
-    def name  // name of the item +Full listing for [[http://www.cpjobling.org.uk/~eechris/at-m42/Examples/lecture07/example15.groovy|Example 15]] is given in the notes.
-    def value // value of the item in game points +
-    def description = '' // a description of the item+
  
-}+----
  
-class WeightyItem extends AbstractItem +The implementation for this is give in Example 15, where ''Portable'' is introduced as a an interface class. An interface declares, but does not define, one or more abstract methods. The abstract class ''AbstractItem'' conforms to the protocol since it //implements// the ''Portable// interface. Notice that ''AbstractItem'' offers a simple implementation for the ''canCarry'' methodWe must explicitly redefine it in the ''WeightyItem'' and ''MigicalItem'' classes (note we use the superclass definitions in both!).
-     +
-    String toString() { +
-        return 'WeightyItem: + super.toString() + "; weight: ${weight}." +
-    } +
-     +
-    Boolean canCarry(Player player) { +
-    return super.canCarry(player) && (weight < player.strength)  +
-    } +
- +
-// ---- properties ------------------------- +
- +
-    def weight = 0 +
-+
- +
-class MagicalItem extends AbstractItem +
- +
-    String toString() { +
-        return 'MagicalItem: + super.toString() + "; potency: ${potency}." +
-    } +
- +
-    Boolean canCarry(Player player) { +
-    return super.canCarry(player&& (player.power >= (potency/5))  +
-    } +
-</code>+
  
 <code groovy 1 | Example 15: The interface calls (at-m42/Examples/lecture07/example15.groovy)> <code groovy 1 | Example 15: The interface calls (at-m42/Examples/lecture07/example15.groovy)>
at-m42/lecture7.1239637825.txt.gz · Last modified: 2011/01/14 12:25 (external edit)