// "favor composition over inheritance" ~Effective Java
class Parent {
def getAll() {
String resp = ""
2.times {
resp += get(it)
}
return resp
}
def get(def i) {
"get PARENT $i\n"
}
}
class Child1 extends Parent {
def get(def i) {
"get CHILD $i\n" // is used by parent's getAll
}
}
class Child2 {
@Delegate Parent p = new Parent() // decorated Parent instance
def get(def i) {
"get CHILD $i\n" // not used by parent's getAll
}
}
Parent c1 = new Child1()
assert c1.getAll() == "get CHILD 0\nget CHILD 1\n" // calls child's get()
assert c1.get(0) == "get CHILD 0\n"
//Parent c2 = new Child2() // Child2 is not a Parent!
Child2 c2 = new Child2()
assert c2.getAll() == "get PARENT 0\nget PARENT 1\n" // calls parent's get()
assert c2.get(0) == "get CHILD 0\n"
Thursday, November 15, 2012
@Delegate vs. Extends
Labels:
delegate,
extends,
inheritance
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment