Search code examples
oopdelegation

Example of delegation in object-oriented programming: Clarification needed


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 in b.bar being printed, since this refers to the original receiver object, b, within the context of a.

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.


Solution

    1. b.foo() calls this.a.foo()

    Because b.a is declared delegated, this.a.foo() is called in the context of b

    1. 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().