-3

The code below shows how method m() can be reused by inheritance. How works for delegation? Thanks!

  class A{
  int m();
  }

 class B extends A{}

 B b =new B()
 b.m();

2 Answers2

3
class B {
    int m() {
        return new A().m();
    }
}

or

class B {
    private A a = new A();
    int m() {
        return a.m();
    }
}

or

class B {
    private A a;

    public B(A a) {
        this.a = a;
    }

    int m() {
        return a.m();
    }
}
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
2

Inheritance means IS-A: "An instance of class B IS-A instance of class A".

Composition means HAS-A: "An instance of class B HAS-A instance of class A".

Like this:

class B {

    private A a;

    public B(A a) { this.a = a; }

    public int m() { return a.m(); }
}

Class B delegates its call to m() to its instance of class A.

It helps if both implement a common interface.

public interface DoSomething {
    int m();
}

class A implements DoSomething {
    public int m() { return 1; }
}

class B implements DoSomething {

    private A a;

    public B(A a) { this.a = a; }

    public int m() { return a.m(); }
}
duffymo
  • 305,152
  • 44
  • 369
  • 561