Abstract classes let you create a base blueprint that other classes can follow. Abstract methods are like empty promises that child classes must fill in.
Abstract classes and methods in C Sharp (C#)
abstract class Animal { public abstract void MakeSound(); public void Eat() { Console.WriteLine("This animal is eating."); } }
An abstract class cannot be instantiated directly.
Abstract methods have no body and must be implemented by subclasses.
abstract class Vehicle { public abstract void StartEngine(); } class Car : Vehicle { public override void StartEngine() { Console.WriteLine("Car engine started."); } }
abstract class Shape { public abstract double GetArea(); } class Circle : Shape { private double radius; public Circle(double radius) { this.radius = radius; } public override double GetArea() => Math.PI * radius * radius; }
abstract class EmptyBase { public abstract void DoSomething(); } // This will cause a compile error if DoSomething is not implemented class Derived : EmptyBase { public override void DoSomething() { Console.WriteLine("Doing something."); } }
This program shows an abstract class Animal with an abstract method MakeSound and a normal method Eat. Dog and Cat classes implement MakeSound differently. We create Dog and Cat objects and call their methods.
using System; abstract class Animal { public abstract void MakeSound(); public void Eat() { Console.WriteLine("This animal is eating."); } } class Dog : Animal { public override void MakeSound() { Console.WriteLine("Woof!"); } } class Cat : Animal { public override void MakeSound() { Console.WriteLine("Meow!"); } } class Program { static void Main() { Animal dog = new Dog(); Animal cat = new Cat(); dog.Eat(); dog.MakeSound(); cat.Eat(); cat.MakeSound(); } }
Time complexity: Abstract methods themselves do not affect time complexity; it depends on the implementation in subclasses.
Space complexity: Abstract classes do not add extra memory overhead beyond normal classes.
Common mistake: Trying to create an object of an abstract class directly causes a compile error.
Use abstract classes when you want to share code and force certain methods to be implemented by child classes. Use interfaces if you only want to define method signatures without any code.
Abstract classes provide a base template that cannot be instantiated.
Abstract methods are declared without a body and must be implemented by subclasses.
They help organize code by sharing common behavior and enforcing specific implementations.