Pages

Thursday, March 28, 2013

What is Abstract method?


Abstract method doesnot provide implementation and forces derived class to override the method.

There are following ways we can make use of Abstract Classes and Methods

1.We can create Non-Abstract methods inside Abstract Class, and Inherited Class can use this method.

See the Example below

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AbstractMethod1
{
    abstract class Test
    {
        public void MethodInAbstract()
        {
            Console.WriteLine("NonAbstract Method Called");
            Console.ReadKey();
        }
    }

    class Inherit : Test
    {
    }
    class Program
    {
        static void Main(string[] args)
        {
            Inherit obj = new Inherit();
            obj.MethodInAbstract();
        }
    }
}

In above program Test is Abstract Class MethodInAbstract is Non Abstractmethod. Another Class Inherit inherited the Abstract Class Test. Now we created object for
Inherit and called the MethodInAbstract method.

More Observations:
Abstract class will starts with keyword 'Abstract'
We can not create object for abstract class
Test obj=new Test(); it will show the error message 'Cannot create an instance of the abstract class or interface 'AbstractMethod1.Test'

2.Abstract method is meant by method which is not having any body, Who ever class inherited this Abstract Class that class must be override the
abstract methods.

Ex:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AbstractMethod2
{
    abstract class Myclass
    {
       public abstract void AbstractMethod();
    }

    class MyInheritedClass : Myclass
    {
        public override void AbstractMethod()
        {
            Console.WriteLine("Abstract method implemented");
            Console.ReadKey();
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            MyInheritedClass obj = new MyInheritedClass();
            obj.AbstractMethod();
        }
    }
}

In above AbstractMethod() is abstract method, which was implemented by derived class MyInheritedClass.

More Observations:
Abstract method must be public and starts with abstract keyword
If we not implement the abstract method in derived class we will get error message ''AbstractMethod2.MyInheritedClass' does not implement inherited abstract member 'AbstractMethod2.Myclass.AbstractMethod()'

0 comments:

Post a Comment