Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I override my interface methods?

Let's say I have an interface as follows.

interface CardHolder : IEnumerable<Card>
{
    /// <summary> ...
    void PutCard(Card card);

    /// <summary> ...
    void PutCards(Card[] card);

    /// Some more methods...
}

I implement it as follows.

public class ArrayCardHolder : CardHolder
{
    private Card[] _cards;
    private int _size = 0;

    public ArrayCardHolder(int capacity)
    {
        _cards = new Card[capacity];
    }

    public void PutCard(Card card)
    {
        if (IsFull())
            throw new Exception("This CardHolder is full. Capacity: " + Capacity());

        _cards[_size++] = card;
    }

    public void PutCards(Card[] cards)
    {
        if (_size + cards.Length > _cards.Length)
            throw new Exception("Adding the Cards would exceed this CardHolder its capacity. Capacity: " + Capacity());

        for (int index = 0; index < cards.Length; index++)
            _cards[_size++] = cards[index];
    }
    public IEnumerator<Card> GetEnumerator()
    {
        for (int index = 0; index < _size; index++)
            yield return _cards[index];
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return this.GetEnumerator();
    }

    ///More methods.

}

Why can I not use the override keyword in my ArrayCardHolder (e.g. public void override PutCard(Card card) { ///implementation } to indicate that the method implements (i.e. overrides) the interface? In that case, the project will refuse to build.

Why does it work however when overriding ToString()? And why doesn't it work when implementing CompareTo(T t) from IComparable<T>?

What should I use instead? I'm worried that the documentation from the interface will not apply to my implementing methods. Such is the case in Java when the @Override annotation is used.

like image 349
Auberon Avatar asked Jul 08 '16 18:07

Auberon


1 Answers

Interface's methods are not overriden, they are implemented. You are confused with abstract/virtual methods which can be overriden.

Example:

public interface IFoo    
{
    void DoA();
}

public abstract class BaseFoo : IFoo
{
    public void DoA() { } // *this HAS to be implemented*
    public virtual void DoB() { } 
}

public abstract class MyFoo : BaseFoo
{
    // *this CAN be implemented, which would override the default implementation*
    public override void DoB() { } 
}

As others metioned, ToString is a virtual method of the base class object, that is why you can override it.

like image 161
Camilo Terevinto Avatar answered Sep 30 '22 07:09

Camilo Terevinto