Loading...

Abstract Classes and Methods in OOP C#

Abstract Classes:

Abstract class is a class that can contain abstract methods, It can be inherited by another abstract classes, you can not create its instance because it may contain Abstract (unimplemented) Methods. If a class consist any abstract method than that call must also be an abstract class. Example:


abstract class Human
{
    //Any valid code goes here
}

class Program
{
    static void Main(string[] args)
    {
        Human h;
        //Error: Cannot create the instance of abstract class       
        h = new Human();       
    }

}

Abstract Functions:

Abstract Methods or Functions are the unimplemented methods that does not contain body. They must be implemented(overridden) in a child class. You can not declare static methods as abstract, override or virtual. Example:


abstract class Human
{
    protected string name;
    public abstract void Display();// abstract methods

  public void anotherMethod()// may contain implemented methods
    {
        Console.WriteLine("anotherMethod() ...");
    }
}

class Student:Human
{
    protected int regNo;
    public override void Display()// abstract classes must be overridden 
    {
        Console.WriteLine("{0} {1}", name, regNo);
    }
}

Thanks to msdn.microsoft.com for knowledge and examples
Hit Like Button if you understood, It helps a lot to keep us Motivated.

0 comments:

Post a Comment

Google+

 
TOP