Taken from https://en.wikipedia.org/wiki/Delegation_(programming):
class A {
void foo() {
// "this" also known under the names "current", "me" and "self" in other languages
this.bar();
}
void bar() {
print("a.bar");
}
};
class B {
private delegate A a; // delegation link
public B(A a) {
this.a = a;
}
void foo() {
a.foo(); // call foo() on the a-instance
}
void bar() {
print("b.bar");
}
};
a = new A();
b = new B(a); // establish delegation between two objects
Calling
b.foo()
will result inb.bar
being printed, sincethis
refers to the original receiver object,b
, within the context ofa
.
Can someone clarify the explanation immediately above? I think I understand the basic principle, but I'm still unsure as to why it would call the foo()
method from class B
.
b.foo()
calls this.a.foo()
Because b.a
is declared delegated
, this.a.foo()
is called in the context of b
a.foo()
calls this.bar()
Because a.foo()
is called in the context of b
, this
keyword inside a.foo()
references b
, not a
. Thus, this.bar()
references b.bar()
.