I can't think of a reason why I shouldn't do this but I wanted to see if I was missing something. If I have a class that implements an interface is there any reason not to have member objects of a different class implementing the same interface?
public class MemberClass implements MyInterface{
}
public class LargerClass implements MyInterface{
private MemberClass memberClass = new MemberClass;
}
Would there be any problems that would apply to most interfaces that would not apply to marker interfaces?
That's absolutely fine, and is often used for delegation, e.g. in the decorator pattern. While it's not actually using interfaces (instead using an abstract base class, Stream
), BufferedStream
is an example of this.
Or for example you could create a "concatenating iterable":
public class Concatenation<T> : IEnumerable<T>
{
private readonly IEnumerable<T> first;
private readonly IEnumerable<T> second;
public Concatenation(IEnumerable<T> first, IEnumerable<T> second)
{
this.first = first;
this.second = second;
}
public IEnumerator<T> GetEnumerator()
{
// Implicitly calls first.GetEnumerator()
foreach (T item in first)
{
yield return item;
}
// Implicitly calls second.GetEnumerator()
foreach (T item in second)
{
yield return item;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
(Enumerable.Concat
in LINQ effectively does this...)
See more on this question at Stackoverflow