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();
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();
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();
}
}
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(); }
}