Introduction
A detailed analysis of Abstract classes and methods in C# with some concrete examples.
The keyword abstract can be used with both classes and methods in C# to declare them as abstract.
The classes, which we can't initialize, are known as abstract classes. They provide only partial implementations. But another class can inherit from an abstract class and can create their instances. You need to mark class members that have no implementation with the abstract modifier. ou also need to label a class containing such members as abstract. A class with abstract members cannot be instantiated with the new operator. You can derive both abstract and non-abstract classes from an abstract base class. Interfaces are implicitly abstract.
They cannot be instantiated, and must be implemented by a non-abstract class. Therefore, you cannot mark interfaces and their members as abstract. You may not combine the abstract modifier with the other inheritance modifier, final. You may not combine either of these inheritance modifiers (abstract and final) with the static modifier.
See the below examples,
Example 1
namespace Abstract
{
abstract class MyAbs
{
public void NonAbMethod()
{
Console.WriteLine("Non-Abstract Method");
}
}
class MyClass : MyAbs
{
}
class Class1
{
[STAThread]
static void Main(string[] args)
{
MyClass mc = new MyClass();
mc.NonAbMethod();
}
}
}
namespace Abstract2
{
abstract class MyAbs
{
public void NonAbMethod()
{
Console.WriteLine("Non-Abstract Method");
}
public abstract void AbMethod();
}
class MyClass : MyAbs
{
public override void AbMethod()
{
Console.WriteLine("Abstarct method");
}
}
class Class1
{
[STAThread]
static void Main(string[] args)
{
MyClass mc = new MyClass();
mc.NonAbMethod();
mc.AbMethod();
}
}
}
For more examples, please see the attachment.