Sobes.tech
Junior — Middle

What are the main differences between abstract and concrete classes in object-oriented programming?

sobes.tech AI

Answer from AI

An abstract class is a class that cannot be instantiated directly and is intended to serve as a base for other classes. It may contain abstract methods (without implementation) that must be implemented in subclasses.

A concrete class is a class that can be instantiated as objects and contains a complete implementation of all its methods.

Main differences:

  • Instantiation: An abstract class cannot be created directly, while a concrete class can.
  • Methods: An abstract class may contain abstract methods without implementation, whereas a concrete class has all methods implemented.
  • Purpose: An abstract class defines a common interface and behavior for its subclasses, while a concrete class implements specific logic.

Example in C#:

abstract class Animal
{
    public abstract void MakeSound(); // abstract method
}

class Dog : Animal
{
    public override void MakeSound()
    {
        Console.WriteLine("Bark");
    }
}

// Animal a = new Animal(); // Error
Dog dog = new Dog();
dog.MakeSound(); // Outputs Bark