Search code examples
javainheritancedelegation

Inheritance vs. Delegation


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

Solution

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