Pamingkas Sevada
Pamingkas Sevada

Reputation: 432

How can I determine the relationship of a class to properties (Abstract and Interface)

according to Aamir in When to use an interface instead of an abstract class and vice versa?

When you derive an Abstract class, the relationship between the derived class and the base class is 'is a' relationship. e.g., a Dog is an Animal, a Sheep is an Animal which means that a Derived class is inheriting some properties from the base class.

Whereas for implementation of interfaces, the relationship is "can be". e.g., a Dog can be a spy dog. A dog can be a circus dog. A dog can be a race dog. Which means that you implement certain methods to acquire something.

But how about the abilities? Like, "A dog can bark", "a cat can jump", "a snake can slither", where will I put these, in an abstract or an interface?

Upvotes: 0

Views: 75

Answers (3)

Memfisto
Memfisto

Reputation: 352

If you have some common abilities, like move, you can have an interface of those and have the abstract class implement those methods (if animals are the only thing you'll work with, then you wouldn't really gain much by having that interface I believe). If you are having specific abilities that would apply only on certain derived classes, have them implement the interface.

Dog barking seems to be an ability only for a single derived class, why not leave it be implemented by that derived class? Having it in the abstract class would mean all animals would be able to bark, but then again having a dog class implement an interface that has bark in it seem a bit weird if dog is your only animal capable of barking.

Side note: interfaces don't necessarily have to be defined as "can be" relationship.

Upvotes: 1

candidus
candidus

Reputation: 129

There's another thing to consider: Your implementation class can implement as many interfaces as you want but you can inherit from only one class directly, abstract or concrete. To put things short: Use interfaces when you can and abstract classes when you have to.

Upvotes: 0

toneo
toneo

Reputation: 129

The ability to do something would probably be best suited to an interface, unless you are looking to provide some default behaviour if the method is not implemented.

Keep in mind that C# does not support inheriting from multiple classes, but does support implementing multiple interfaces. This allows for some flexibility. Such as this:

interface IBreathes()
{
    void Breathe();
}

interface IMoveable()
{
    void Move(int x, int y);
}

class Snake : Animal, IBreathes, IMoveable
{
    void Breathe()
    {
        ...
    }

    void Move(int x, int y)
    {
        ...
    }
}

For the above example use of abstract classes would be fine, but with large, complex projects it may become quite frustrating to work around the single-inheritance issue.

Upvotes: 0

Related Questions