Abstract classes and Interfaces are today’s items of discussion.

Agenda

Sealed

Sealed modifier prevents other classes from inheriting from it.

Please see following example how to use it.

sealed class A
{

}

//Gives an error, due to sealed class A
class B : A
{

}

Abstract classes

In C#, the abstract modifier is used to define an abstract class. Abstract class cannot be instantiated, and is frequently either partially implemented, or not at all implemented.

One key difference between abstract classes and interfaces is that a class may implement an unlimited number of interfaces, but may inherit from only one abstract (or any other kind of) class.

An example of abstract class:

public abstract class Country
{
    public string Name { get; set; }
    public string Currency { get; set; }

    public void PrintInformation()
    {
        Console.WriteLine(Name);
        Console.WriteLine(Currency);
        Console.WriteLine(this.GetFlagDescription());
    }

    //Abstract function.
    //Pay your attention. A method w/o implementation.
    public abstract string GetFlagDescription();
}

Some inherited class from out abstract class. Sure, derived class can be instantiated. Pay your attention this class is sealed.

sealed class Usa: Country
{
    public override string GetFlagDescription()
    {
        return "Thirteen horizontal stripes alternating red and white;" +
                "in the canton, 50 white stars of alternating numbers of " +
                "six and five per row on a blue field";
    }
}

Interfaces

An interface is not a class. An interface is defined as a syntactical contract that all the classes inheriting the interface should follow. An interface contains only the signatures of methods, properties, events or indexers. We’ll talk later about events and indexers. A class or struct that implements the interface must implement the members of the interface that are specified in the interface definition.

Simple interface to have been defined with one property and method.

public interface IAlcohol
{
    double AlcoholByVolume { get; set; }

    double GetMaximumAllowedWightForHuman();
}

References

Presentation

Lesson8 from Alex Honcharuk