Friday, March 25, 2011

different B/w Virtual Method and Abstract Method.


- If an abstract class's method is marked as abstract and any class is derived from the abstract class, then the derive class must implement(override) the base class abstract method.
- If a class's method is marked as virtual, then it leaves an option for the derive class to override it



main difference is that, when we us virtual class it means all its methods are required to be abstract. but if we use abstract class then some of its methods will be abstract but not all.
virtual function or abstract function are function without definition.




An abstract method is used in a abstract class and a virtual method is used in a normal class.
Both are used to override the methods in a derived class.
A virtual method is declared with keyword virtual and a abstract method is declared with keyword abstract.
A virtual method has some implementation and an abstract method do not have any implementation body.

Example:

Virtual Method:-

Class A
{
Virtual Void Display()
{
Console.WriteLine("Display Me from class A");
}
}

class B : A
{
override void Display()
{
Console.WriteLine("Display me from class B");
}
}
class MainClass
{
Static void Main()
{
A objA= New B();
objA.Display();
}
}


The out put here will be "Display me from class B"

Abstract Method:

abstract class A
{
abstract void Display()----As class is declared abstract so method may or may not have declared as abstarct as this is declared as abstract so it should not have implemenation here.
}

class B : A
{
public override void Display()
{
Console.WriteLine("Display me from class B");
}
}

class MainClass
{
static void Main()
{
A objA = new B();

objA.Display();
}
}

The out put here will also be "Display me from class B"




When a class contains abstract method, the class must be declared as abstract
Abstract method has no implementation
Deriving class must provide implementation
Abstract methods cannot be overridden

A class can have virtual method
Virtual method has implementation
You can override virtual methods








No comments:

Post a Comment