What is Abstract Class in C#

Beginner

2019-04-09

What is Abstract Class in C# ?

In Object Oriented Programming, an abstract class is a class that is not completely implemented. A child class can inherit from the abstract class and implement it.


Object Oriented Programming Inheritance

In OOP languages, a core concept is class inheritance, A child class inherit from a parent class and inherit all it's public methods and properties. So they will be accessible from the child classes too.

In case of Abstract classes, a parent that is defined as an abstract class will have partial implementation of some methods and a child that inherits from the abstract class can provide an implementation for those functions marked as abstract.


Example of Abstract Class in C#


DataProvider class provides a fetch method. child classes can use the base implementation or override it and provide it's own implementation.

Abstract Class Usage

With Abstract Class you can create Templates for future classes by providing a template that all contains some implementation and all the future classes can continue the implementation with the same methods prototype.

Provides functionality that child classes can utilize later and extend it.

When you have Partial implementation only for the methods and wants to provide the ability for child classes to provide an implementation.


Abstract Class Interview Questions

Abstract Classes is a topic that is asked frequently in C# and OOP programming Interviews. Below are the common questions.

Can abstract class contain private methods ?

Yes. Abstract classes in C# can contain private methods but these methods will not be inherited in the child class.

Abstract Method in non Abstract class ?

No. You can't have abstract methods inside non abstract class.

Can you have non abstract method in abstract class ?

Yes. non abstract methods are allowed inside abstract classes

Can you instantiate an object from an abstract class ?

No. Abstract classes are considered not complete yet. You can not instantiate an object from an abstract class.


What is the Difference between Abstract Class and Interface ?

  1. Interfaces provides a unified way of communication between classes by providing a set of method prototype declarations that each class mush follow and implement.
  2. If a class implements an interface, it must implement all it's methods
  3. Interfaces cannot have private methods in C#.
  4. Interface methods cannot have body, just the prototype.
  5. While abstract classes can contain private methods and can have methods implementation body.
  6. You can use an interface when you don't have any implementation for the class.
  7. And use an abstract class when you have partial implementation and want to provide a template for future classes.