Posted in .Net Basics, C# 4.0

Abstract Classes in .Net

An abstract class means that, no object of this class can be instantiated, but can make derivations of this.

Its a special type of class that cannot be instantiated. (So why we need that ??) There are some reasons, an Abstract class is only to be sub-classed. That means it enforces some contracts or say methods to all the subclasses.

Here is a basic sample of abstract class and how to access their abstract and non abstract methods.

abstract class testDemo
    {
        public void callme() // non abstract method
        {
            // Some implementation
        }

        abstract public void ImplementMe(); // abstract method
    }

    class Child : testDemo
    {
        //implement the abstract method
        public override void ImplementMe()
        {
            throw new NotImplementedException();
        }
    }

This is how you can access methods of the abstract class.

 public void TestMethod()
        {
            Child obj = new Child();
            obj.callme();       // call to a non abstract method
            obj.ImplementMe();  // call to an abstract method which is implemented on the Child class
        }

An abstract class can also have abstract properties as well, derived class has to implement this property.

An Abstract class cannot be a sealed class. Following is not valid

  abstract sealed class testDemo {}

An abstract Method cannot be Private. Access modifier of the abstract method must be the same in both abstract class and its derived class. Otherwise it will be detected as error by compiler.

private abstract int myProp(); // incorrect

An Abstract method can’t be virtual as it is implicitly virtual.

An abstract member can’t be static but an abstract method can be a static one.

Hope this help someone.

Advertisements