First off, I know next to nothing about language theory, and I barely know any other languages except Java, but I had an idea that I think would be cool, but I need you guys to tell me:
a: why it sucks
b: how language x has had that for years
c: how my mind sucks
d: all of the above
The idea would give composition the same ease of code reuse that extends
does.
So if you had a class like this:
public interface A { public void methodInA(); }
And then you had a class like this:
public class B { private composed A; public B() { // construct A within constructor } }
You would then be able to do this:
B myB = new B(); myB.methodInA();
Without having to add in the delegation in B's class. But you could also do the same as with inheritance, ie:
@Overrides public void methodInA(){ // B's own delegation method }
Disadvantages include:
- methods are hidden in the source code, making it less obvious where the call is coming from, but this is also the case with
extends
- if composed fields share the same method signature there needs to be a conflict resolved (how do conflicting interfaces solve this?)
- if you wanted to have several composed fields of the same type, there would be an obvious conflict for which field to delegate to
- probably 100 other things I've not thought of
Like I say, I'm obviously no language theorist, and I haven't spent ages thinking about it, the idea just popped in my head and I wanted to know how wrong I am. I just think it would be kind of cool.