user4422282
user4422282

Reputation:

Inheriting one overloaded method

I'm fairly new to C# and OOP, and I have a question in regards to inheritance.

Say I have:

public abstract class Command
{
    protected Command()
    {
    }

    public abstract string Execute();

    public abstract string Execute(object o);
}

public class CommandA : Command
{
    public override string Execute()
    {
    }
}

public class CommandB : Command
{
    public override string Execute(object o)
    {
    }
}

There are obvious errors due to CommandA not implementing Execute(object o) and CommandB not implementing Execute().

My question, then, is whether there is code I need to implement to avoid these errors? Are empty methods allowed?

Upvotes: 0

Views: 52

Answers (1)

Rob
Rob

Reputation: 27377

You're abusing the use of abstract if you're expecting sub-classes to not actually implement some of the methods. abstract is used to enforce that the base class must implement the functionality. What should happen if someone called new CommandB().Execute()?

In some cases, a design may be incorrect and you end up in the situation you're in. In these cases, its somewhat common (though in my opinion a code smell), to do the following:

public class CommandA : Command
{
    public override string Execute()
    {
    }

    public override string Execute(object o)
    {
        throw new NotImplementedException();
    }
}

A somewhat cleaner approach:

public abstract class Command
{
    protected Command()
    {
    }

    public abstract string Execute(object o = null);
}

Though you're still going to have to deal with the fact that someone may pass an object to CommandA.

If the commands have such different behaviour, it's likely they shouldn't both be subclassing the same abstract class.

Upvotes: 1

Related Questions