Complete C# Tutorial

Abstract and Virtual Method in C# – Simple Explanation with Examples

Hey there, coder! πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» Ever been confused about abstract and virtual methods in C#? You’re not alone! These two concepts are super important in object-oriented programming, and today, we’ll break them down in the simplest way possible.

By the end of this lesson, you’ll not only understand these methods but also know when to use them. Sounds good? Let’s dive in! πŸš€

1️⃣ What is an Abstract Method?

An abstract method is a method without a body that must be overridden in a derived class. It’s like a blueprint for a method, telling child classes:

“Hey! You must implement this method, but I won’t define it for you!”

Β 

Syntax of Abstract Method

				
					abstract class ParentClass  
{
    public abstract void ShowMessage();  // No body
}
				
			

βœ”οΈ The abstract keyword makes the method mandatory for child classes.
βœ”οΈ The class containing an abstract method must be declared abstract.

2️⃣ What is a Virtual Method?

A virtual method is a method with a default implementation in the parent class that child classes can override if needed.

Think of it like:

“You can change how this works in child classes, but you don’t have to!”

Β 

Syntax of Virtual Method

				
					class ParentClass  
{
    public virtual void ShowMessage()  // Has a body
    {
        Console.WriteLine("This is a message from ParentClass");
    }
}
				
			

βœ”οΈ The virtual keyword allows overriding.
βœ”οΈ Unlike abstract, child classes are not forced to override it.

3️⃣ Abstract Method vs. Virtual Method – Key Differences

Feature Abstract Method Virtual Method
Implementation No body (must be implemented in a child class) Has a default body
Usage Forces derived classes to override it Allows overriding but doesn’t force it
Declaration In an abstract class only In any normal or abstract class
Flexibility Less flexible (you must override it) More flexible (you may override it)

4️⃣ Real-World Example – Restaurant Menu πŸ•

Imagine you own a restaurant, and you have different types of dishes.

Β 

Abstract Method:

Every dish must have a Prepare() method, but the actual preparation depends on the dish type.

Β 

Virtual Method:

A dish has a Serve() method with a default implementation, but some dishes might override it for special serving styles.

5️⃣ Example 1 – Abstract Method in Action πŸš€

Let’s implement abstract methods using a Shape class!

				
					using System;

abstract class Shape  
{
    public abstract void Draw();  // No body
}

class Circle : Shape  
{
    public override void Draw()  
    {
        Console.WriteLine("Drawing a Circle");  
    }
}

class Square : Shape  
{
    public override void Draw()  
    {
        Console.WriteLine("Drawing a Square");  
    }
}

class Program  
{
    static void Main()  
    {
        Shape shape1 = new Circle();
        Shape shape2 = new Square();

        shape1.Draw();  // Output: Drawing a Circle
        shape2.Draw();  // Output: Drawing a Square
    }
}
				
			

Explanation:

βœ… Draw() is an abstract method β†’ Must be implemented in child classes.
βœ… Both Circle and Square override Draw() with their own logic.
βœ… Polymorphism allows us to use Shape as a reference to different objects.

6️⃣ Example 2 – Virtual Method in Action πŸš€

Now, let’s see virtual methods in a Car class!

				
					using System;

class Car  
{
    public virtual void Start()  
    {
        Console.WriteLine("Starting the car...");  
    }
}

class SportsCar : Car  
{
    public override void Start()  
    {
        Console.WriteLine("Starting the sports car with a roar!");  
    }
}

class Program  
{
    static void Main()  
    {
        Car myCar = new Car();
        myCar.Start();  // Output: Starting the car...

        Car mySportsCar = new SportsCar();
        mySportsCar.Start();  // Output: Starting the sports car with a roar!
    }
}
				
			

Explanation:

βœ… Start() is a virtual method in Car.
βœ… SportsCar overrides Start() with a different message.
βœ… If SportsCar didn’t override Start(), it would use the default implementation.

7️⃣ When to Use Abstract vs. Virtual Methods? πŸ€”

βœ… Use Abstract Methods when you want to force child classes to implement a method.
βœ… Use Virtual Methods when you want to provide a default implementation but allow modification.

Example Scenarios:

βœ… Abstract Method β†’ Shapes (Circle, Square must have Draw()).
βœ… Virtual Method β†’ Car starting behavior (Some cars may have custom Start()).

πŸ”₯ Quick Recap

βœ”οΈ Abstract Method β†’ No body, must be overridden.
βœ”οΈ Virtual Method β†’ Has a body, can be overridden.
βœ”οΈ Abstract Class contains abstract methods.
βœ”οΈ Virtual Methods allow flexibility while maintaining a base implementation.

Β 

Next What? 🎯

Great job! πŸŽ‰ You just learned about Abstract and Virtual Method in C#! Now you know when to use them, their differences, and how they work in real-world scenarios.

πŸš€ Next up: In the next chapter, you’ll learn about Method Overriding vs. Method Hiding in C# – an important topic to avoid unexpected behavior in your code. Stay tuned! πŸ˜‰

Leave a Comment

Share this Doc

Abstract and Virtual methods

Or copy link