Interfaces and abstract classes in C#

✓ Interface – An interface does not contain any code or data; it just specifies the methods and properties, and a class that inherits from the interface must provide implementation.

✶ A class can inherit from another class and implement an interface at the same time.
✶ You’re not allowed to define any constructors in an interface.
✶ You’re not allowed to define a destructor in an interface.
✶ You cannot specify an access modifier for any method.
✶ An interface is not allowed to inherit from a structure or a class, although an interface can inherit from another interface.

✓ Explicitly implementing an interface

interface ILandBound
{
    int NumberOfLegs();
}
interface IJourney
{
    int NumberOfLegs();
}

class Horse : ILandBound, IJourney
{
    int ILandBound.NumberOfLegs()
    {
        return 4;
    }
    int IJourney.NumberOfLegs()
    {
        return 3;
    }
}

Horse horse = new Horse();

IJourney journeyHorse = horse;
int legsInJourney = journeyHorse.NumberOfLegs();

ILandBound landBoundHorse = horse;
int legsOnHorse = landBoundHorse.NumberOfLegs();

✓ Abstract classes – To declare that creating instances of a class is not allowed, you can declare that the class is abstract by using the abstract keyword.

✓ Abstract methods – An abstract class can contain abstract methods. An abstract method is similar in principle to a virtual method, except that it does not contain a method body. A derived class must override this method.

abstract class GrazingMammal : Mammal, IGrazable
{
    ...
    void IGrazable.ChewGrass()
    {
         // common code for chewing grass
        Console.WriteLine("Chewing grass");
    }
}
class Horse : GrazingMammal, ILandBound
{
    ...
}
class Sheep : GrazingMammal, ILandBound
{
    ...
}

✓ Sealed classes – With C#, you can use the sealed keyword to prevent a class from being used as a base class if you decide that it should not be.

sealed class Horse : GrazingMammal, ILandBound
{
    ...
}

If any class attempts to use Horse as a base class, a compile-time error will be generated.

✓ Sealed methods – You can also use the sealed keyword to declare that an individual method in an unsealed class is sealed. This means that a derived class cannot override this method.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s