Wednesday 27 February 2013

Abstract Methods and Abstract Classes

A method without any method body is known as a Abstract method. It will have only the defination for the method the method and to declare any method as abstract we need to use abstract modifier on the method.    
   A class under which we define abstract members is  known as a abstract class and it also has to be defined using abstract modifier.

 abstract modifier
{
   public abstract void Add(int x,int y);
}

The concept of abstract method is near similar to the concept of method overriding were in case of Method Overriding if any members of parent class are declared as virtual those methods can be re- implemented under the child class using the override modifier.

Add a classAbsParent.cs and write the following code:
using System;

namespace CSharpConsole
{
    abstract class AbsParent
    {
        public void Add(int x, int y)
        {
            Console.WriteLine(x + y);
        }
        public void Sub(int x, int y)
        {
            Console.WriteLine(x -y );
        }  

        public abstract void mul(int x, int y);
        public abstract void div(int x,int y);
        
    }
 }
//Add another class AbsChild.cs and write the following code:
using System;
namespace CSharpConsole
{
    class AbsChild: AbsParent
    {
        public override void  mul(int x, int y)
      {
       Console.WriteLine(x*y );
      }

        public override void  div(int x, int y)
      {
       Console .WriteLine (x/y );
      }
        
      static void Main()
        {
            AbsChild c = new AbsChild();
            c.Add(20, 12);
            c.Sub(15, 5);
            c.mul (5, 5);
            c.div (10, 5);
            Console.ReadLine();
      }
    }
}