Abstract Methods
The abstract method is same as “pure virtual functions” in C++.
The abstract method can be declared with “abstract” keyword like this:
public abstract void samplemethod();
The abstract method doesn’t contain method definition; it contains only method declaration as above.
The abstract methods can be declared only within abstract classes.
Abstract Classes
A class that is declared with “abstract” keyword is called as “abstract class”.
abstract class classname
{
}
Rule: If a class contains at least one abstract method, that class should be declared as abstract class.
The abstract class can contain abstract methods, non-abstract class and normal data members also.
Note: You can’t create an object for the abstract class. It can be inherited from another non-abstract class.
The non-abstract class, that inherits the abstract class, should implement the definition(s) (with “override” keyword) for all of the abstract methods declared in the abstract class.
Note: The access modifiers used in the base and derived classes for the abstract methods should be same.
Implementation Syntax
abstract class abstractclassname
{
//data members if any
//non-abstract methods if any
accessmodifier abstract returntype methodname(arguments);
}
class derivedclassname : abstractclassname
{
accessmodifier override returntype methodname(arguments)
{
//method body
}
}
: Abstract Classes and Methods
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace AbstractDemo
{
//abstract class
abstract class MyBaseClass
{
public abstract void FirstMethod();
public void SecondMethod()
{
Console.WriteLine("This is Non-Abstract Method");
}
}
//non-abstract class
class MyDerivedClass : MyBaseClass
{
public override void FirstMethod()
{
Console.WriteLine("This is Abstract Method");
}
}
class Program
{
static void Main(string[] args)
{
MyDerivedClass s = new MyDerivedClass();
s.FirstMethod();
s.SecondMethod();
Console.Read();
}
}
}