Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class implementing interface containing same interface

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?

like image 451
limeandcoconut Avatar asked Dec 15 '25 01:12

limeandcoconut


2 Answers

I see no problem, just two classes that happen to implement the same interface.

I'd love to hear the design justification that made such a thing necessary, but I don't believe the compiler or runtime will complain.

like image 62
duffymo Avatar answered Dec 16 '25 19:12

duffymo


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...)

like image 30
Jon Skeet Avatar answered Dec 16 '25 18:12

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!