Skip to content

Instantly share code, notes, and snippets.

/TestTraitEx3.groovy
Created Apr 23, 2014

Embed
What would you like to do?
class Item {
String name
int price
}
trait Trader {
// property
int availableMoney = 0
private int tradesDone = 0
// method
def buy(Item item) {
if (item.price <= availableMoney) {
availableMoney -= item.price
tradesDone += 1
println "${getName()} bought ${item.name}"
}
}
def sell(Item item) {
}
// abstract method
abstract String getName()
}
class Merchant implements Trader {
String name
// 實做抽象方法
String getName() {
return this.name
}
}
def bike = new Item(name: 'big red bike', price: 750)
def paul = new Merchant(name: 'paul')
paul.availableMoney = 2000
paul.buy(bike) // prints "paul bought big red bike"
println paul.availableMoney // 1250
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.