What is Abstract and
Virtual Method?
Abstract Method:
Abstract methods are that type of method which is created
only for signature only in base class. Means it is created in base class with
abstract keyword but it has no body implementation.
For example:
Abstract public void Display ( );
An abstract class must be overridden in child class with
override keyword.
1.
Note: An
abstract modifier can be used with classes, methods, properties, indexers and
events.
2.
If class
contains abstract member then class must be created with abstract modifier.
a.
Example: abstract class base class
3. An abstract class must be overridden using
override keyword in child class. If you miss to override them, program will raise compile
time error.
4.
An abstract class cannot be instantiated. Means
you cannot create object of abstract class with new keyword.
5.
An abstract method has no method body. The
method declaration ends with semi colon (;) and after that there is no curly
braces ({}).
6.
Example:
7. abstract class baseclass
8. {
9. public int num = 5;
10. public abstract void Display(string name);
11. }
12. class childclass : baseclass
13. {
14. public override void Display(string name)
15. {
16. Console.WriteLine("Hello :" + name);
17. }
18. }
19. class Program
20. {
21. static void Main(string[] args)
22. {
23. baseclass obj = new childclass();
24. obj.Display("Aditya");
25. Console.ReadLine();
26. }
27.
}
Output: Hello Aditya
Virtual Method:
There may be very long definition of Virtual Method but I
kept it simple and short. A virtual method can be overridden or cannot be
overridden by child class. It is upon programmer choice. It gives flexibility
to direct use of virtual method or add additional functionality in it by
overriding it.
Following example have a base class which has a virtual
method Display(). There is two child class is created. Child1 is overriding the
virtual method and adding own message where child2 is displaying direct message
of virtual method.
Programming Example
class baseclass
{
public virtual void Display()
{
Console.WriteLine("I am base class Virtual
Method");
}
}
class child1 : baseclass
{
public override void
Display()
{
Console.WriteLine("I am child class");
}
}
class Program
{
static void Main(string[] args)
{
baseclass obj = new child1();
obj.Display();
Console.ReadLine();
}
}
OutPut : I am child 1 class