Abstract classes and methods in C Sharp (C#) - Time & Space Complexity
When using abstract classes and methods, it's important to understand how the program runs as input grows.
We want to know how the time to complete tasks changes when using these features.
Analyze the time complexity of the following code snippet.
using System;
using System.Collections.Generic;
abstract class Animal
{
public abstract void Speak();
}
class Dog : Animal
{
public override void Speak() { Console.WriteLine("Woof"); }
}
class Program
{
public static void MakeAnimalsSpeak(List<Animal> animals)
{
foreach (var animal in animals)
animal.Speak();
}
}
This code defines an abstract class with an abstract method, then calls that method on a list of animals.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The foreach loop calling
Speak()on each animal. - How many times: Once for each animal in the list (n times).
Each animal in the list causes one call to Speak(). So, as the list grows, the work grows evenly.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 calls to Speak() |
| 100 | 100 calls to Speak() |
| 1000 | 1000 calls to Speak() |
Pattern observation: The number of operations grows directly with the number of animals.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of animals.
[X] Wrong: "Using abstract methods makes the program slower in a way that changes the time complexity."
[OK] Correct: Calling abstract methods adds a tiny fixed cost, but the overall time still grows linearly with input size.
Understanding how abstract classes affect performance shows you grasp both design and efficiency, a useful skill in real projects and interviews.
"What if the Speak() method itself contained a loop over a list? How would that change the time complexity?"