Abstract classes are prefixed with abstract keyword and can only be used as base classes. These are incomplete classes and we can create an instance of an abstract class. It gives compile error if we create an object to it.
Abstraction is the process of hiding details and showing only the required things. This can be done by using Abstract classes and Interfaces.
An Abstract method is a default virtual method and does not have any method body, it just has a definition. These abstract methods should be implemented by the derived class by overriding it otherwise the derived class will be an abstract class.
An Abstract can have both abstract methods and normal methods.
Example 1: Abstract class with abstract and normal methods.
using System;
namespace SampleProgram {
abstract class MySample {
public abstract void Greet(); // abstract method
public void Talk() {
Console.WriteLine("How are doing ?");
}
}
}
Example 2: Abstract class used as a base class
using System;
namespace SampleProgram {
abstract class MySampleBase {
public abstract void Greet(); // abstract method
public void Talk() {
Console.WriteLine("How are you doing ?");
}
}
class MySampleChild: MySampleBase {
public override void Greet() // abstract method implemented
{
Console.WriteLine("Hello Good Morning !");
}
public static void Main(string[] args) {
MySampleChild objChild = new MySampleChild();
objChild.Greet();
objChild.Talk();
}
}
}
The output will be:
Hello Good Morning!
How are you doing?
Example 3: Abstract class used as a base class and child class MySampleChild is still abstract as it is not
implemented an abstract method of MySampleBase.
using System;
namespace SampleProgram {
abstract class MySampleBase {
public abstract void Greet(); // abstract method
public void Talk() {
Console.WriteLine( "How are you doing ?");
}
}
abstract class MySampleChild: MySampleBase {
public void Sing() {
Console.WriteLine("LaLa La La");
}
}
class MySample: MySampleChild {
public override void Greet() // abstract method implemented
{
Console.WriteLine("Hello Good Morning !");
}
public static void Main(string[] args) {
MySample obj = new MySample();
obj.Greet();
obj.Talk();
obj.Sing();
}
}
}
The output will be:
Hello Good Morning!
How are you doing?
LaLa La La