C# Abstract Classes

What is an Abstract Class?

An abstract class is a class that cannot be used to create objects directly.

It serves as a base class for other classes and is used to define common structure and behavior.

Loading...
Output:

Abstract Methods

An abstract method is a method without a body.

Any class that inherits from an abstract class must provide an implementation for all abstract methods.

Loading...
Output:

Concrete Methods

Abstract classes can also contain normal methods with implementations.

These methods can be reused by all child classes.

Loading...
Output:

Using Abstract Classes

You cannot create an object of an abstract class directly.

Instead, you create objects of classes that inherit from it.

Loading...
Output:

Constructors in Abstract Classes

Abstract classes can have constructors, which are called when a subclass object is created.

This is useful for initializing shared data.

Loading...
Output:

Abstract Class vs Interface

Both abstract classes and interfaces are used for abstraction, but they have key differences.

  • Abstract class: can contain fields, constructors, and methods
  • Interface: defines behavior only
  • Abstract class: a class can inherit only one
  • Interface: a class can implement multiple

Why Use Abstract Classes?

Abstract classes help you define a common structure while allowing flexibility in implementation.

  • Encourages code reuse
  • Defines required behavior
  • Supports polymorphism

Real-World Example

Different shapes can share a base structure but calculate or draw differently.

Loading...
Output:

Practice

Create an abstract class Shape with a Draw() method. Then create Circle and Rectangle classes that implement it.

Loading...
Output:

Need Help?