Click here to Skip to main content
15,888,816 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Despite my head hurting with the stuff I have read, I am struggling to understand specifically what is wrong with the following:

C#
public interface IAnimal
{
    int Age();
    int NumLegs();
}

public interface IBird : IAnimal
{
    bool CanFly();
}

public interface IMammal : IAnimal
{
    int RunningSpeed();
}

public abstract class AnimalBase : IAnimal
{
    public abstract int Age();
    public abstract void PrintAge();
    public override int NumLegs() { return 4; } // Error!
};

public class Sparrow : AnimalBase, IBird
{
    public override void PrintAge() { Console.WriteLine( $"Sparrow is {Age()} years old." ); }

    public override bool CanFly() { return true; } // Error!

    public override int Age() { return 3; }
}


I have a couple of errors (so far):

In my class AnimalBase, I get an error saying 'AnimalBase.NumLegs() - No suitable method found to override'. Why? AnimalBase implements IAnimal so why can't it see the method declaration in the interface?

And why is the abstract Age() in AnimalBase okay? I am guessing here that I am simply declaring a brand new method that has nothing to do with the declaration in the interface, but shouldn't I get some kind of warning that I am kind-of 'hiding' the interface declaration?

The second error is exactly the same 'Sparrow.CanFly() - No suitable method found to override'. Again why? Sparrow implements IBird, so why can't it see IBird.CanFly()?

Any help understanding this might save my remaining hair.

What I have tried:

I have read and read, and I have found lots of examples that do work but no explanation of why what I am trying to do is apparently wrong.
Posted
Updated 20-Dec-16 4:40am

1 solution

Well, your abstract class declares an override member NumLegs - which has no base class implementation to override. What you need is to declare it as virtual which allows derived classes to override it:
C#
public virtual int NumLegs() { return 4; } 
If they do, then the "new" version will be called, if they don't, then the base class version will be used, and 4 will be returned.

The same problem exists with CanFly: interface methods cannot be overridden as they don;t have a base class implementation to override. In this case, just remove the keyword:
C#
public bool CanFly() { return true; } 

and your errors will disappear.
 
Share this answer
 
Comments
Patrick Skelton 20-Dec-16 10:36am    
Arrrgghhh... think my brain has already broken up for Christmas. It is so frustratingly obvious now you have explained it. Thank you!
OriginalGriff 20-Dec-16 14:24pm    
You're welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900