Is there a beautiful design to delegate implementation of an interface?

Let's say we have interface:
public interface I {
 int a();

 int b();
}


Is its implementation:
public class IR implements I {

@Override
 public int a() {
 return 1;
}

@Override
 public int b() {
 return 2;
}

}


I want to build a class which will implement I and to delegate all requests to the I to the instance IR. Can be done via composition:
public class A implements I {
 Delegat IR = new IR();

@Override
 public int a() {
 return delegat.a();
}

@Override
 public int b() {
 return delegat.b();
}

}


Not nice. You can, of course, through inheritance:
public class B extends IR {

}


But it introduces its own limitations, for example, I can't change the delegate in the process of life. So I want through composition.

It is clear that Java here I can not help. And is there in other languages constructions like:
class B implements I {
 Delegat IR = new IR();

 implements I by the delegate; 
}
July 8th 19 at 12:18
1 answer
July 8th 19 at 12:20
Not quite clear what you want. Rather, what you want - clearly, it is not clear why.

If you want absolutely all methods delegate to an instance IR - why don't you just return the instance via the IR interface I of object A - why yourself A to implement I?

If A mediation is still necessary, it means that you want to give it some meaning. I.e. once you want to A himself I realized, it means that you want it to hide the fact that the call is actually delegated to the instance IR.

Once you want the fact of delegation were hidden from the client class A, it is likely, over time, you will want to change the logic of delegation and delegate, for example, to IR, but to a different implementation of the interface I (otherwise, why are you such a concealment of the fact of delegating to IR). And if so, then it is logical that you must explicitly implement methods delegating themselves to the methods of IR.

To what I it everything? Of course, you can imagine that the code delegate is generated automatically based on the design like your (implements I by a delegate), but: a) it is quite a special case, to add to the language a syntax sugar for this, plus probably have a number of implementation issues that do not have a clear answer; b) I think is impossible in a language with powerful macros, but I come to mind only those that you hardly will use, for example, Nemerle or Lisp. Oh, and the C++ preprocessor that can be done.
After sending the question got in Kotlin. It has: https://kotlinlang.org/docs/reference/delegation.html - Alvina_Crona commented on July 8th 19 at 12:23
well, just what you are looking for) I Have to say, the proposed syntax is very neat and logical. - Breana_Leffl commented on July 8th 19 at 12:26

Find more questions by tags Patterns of designingOOPProgramming languages