java – Delegating Interface Implementation

Question:

There is a certain interface A and there is its successor interface B I have an object of interface A I need to create a class that implements interface B

The question is, apart from directly declaring all methods from A and calling the corresponding methods, the object has no other way to implement it?

interface A  {
  void SomeMethod1(...);
  int SomeMethod2(...);
  ........
}

interface B extends A {
  ........
}

class MyClass implements B {
  private A obj;
  void SomeMethod1(...) {
    obj.SomeMethod1(...);
  }

  int SomeMethod2(...) {
    return obj.SomeMethod2(...);
  }
  ........
}

The class that implements A unknown and not available. So that it will not be possible to inherit.

Answer:

Inspired by the advice of @ YuriSPB, Did this:

  1. Объявил интерфейс

    interface DelegateA extends A {
      A getObj();
    
      @Override
      default void SomeMethod1(...) {
        getObj().SomeMethod1(...);
      }
    
      @Override
      default int SomeMethod2(...) {
        return getObj().SomeMethod2(...);
      }
      ............
    }
    
  2. Объявил интерфейс B

    interface B extends A {
      ........
    }
    
  3. Сделал реализацию

    class MyClass implements B, DelegateA {
      private A obj;
    
      @Override
      A getObj() {
        return obj;
      }
    }
    

I like this method more than the one proposed by Yuri, because interface B now independent of any delegates and can be implemented autonomously

Scroll to Top