An abstract class is a class that cannot be instantiated directly (i.e., you cannot create objects of it directly). Instead, it serves as a base class for other classes. An abstract class can contain abstract methods (methods without implementation), regular methods (with implementation), properties, fields, and events.
Syntax:
public abstract class ClassName
{
// Abstract method (no implementation)
public abstract void AbstractMethodName();
// Regular method (with implementation)
public void RegularMethodName()
{
Console.WriteLine("This is a regular method.");
}
}
Important Features of an Abstract Class
1. It cannot be instantiated directly. You cannot create an object of an abstract class.
2. It can contain both abstract and non-abstract methods.
3. It may contain fields, properties, and events.
4. A class that contains an abstract method must itself be marked as abstract.
5. Derived classes are required to implement abstract methods (unless the derived class is also abstract).
Abstract Method
An abstract method is a method defined in an abstract class that has no implementation in the abstract class itself. The derived classes must provide an implementation for this method.
Important Features of an Abstract Method
It is declared using the abstract keyword.
It has no body or implementation in the abstract class.
Derived classes are required to provide the method implementation.
An abstract method must be in an abstract class.
Syntax:
public abstract void AbstractMethodName();
Example:
using System;
// Abstract class Animal (base class)
public abstract class Animal {
// Abstract method (does not have a body)
public abstract void makeSound();
// Regular method (does have a body)
public void eat() {
Console.WriteLine("Animal eat food.");
}
}
// Derived class
public class Dog : Animal {
// Providing implementation for abstract method makeSound()
public override void makeSound() {
Console.WriteLine("Dog bark");
}
}
public class MyProgram {
static void Main(String[] args) {
// Creating an object of Dog class
Animal dog = new Dog();
dog.makeSound(); // Calls Dog's makeSound() method
dog.eat(); // Calls eat() method from Animal class
}
}
Output:
Animal eat food.
Explanation:
- Animal is an abstract class.
- makeSound() is an abstract method, which means every class that inherits from Animal (like Dog) must provide its own implementation of makeSound().
- eat() is a regular method in the abstract class Animal, and Dog can use it as is.