Abstract class in C#

What is an abstract class? This type of question is often asked by interviewers, so due to that I have decided to write this article to help job seekers and anyone who wants to learn about abstract classes. So let us start from the basics so beginners can also understand.

What is Abstract Class ?

If the class is created for the purpose of providing common fields and members to all subclasses then this type of class is called an abstract class.
 
Syntax of creating an abstract class
 
An abstract class is created in C# using the abstract keyword.
 
Example

abstract public class Pen
Use of Abstract Class
There may sometimes be a situation where it is not possible to define a method in a base class and instead every derived class must override that method. In this situation abstract classes or methods are used.
 
Abstract methods have no implementation, so the method definition is followed by a semicolon instead of a normal method block. Derived classes of the abstract class must implement all abstract methods. When an abstract class inherits a virtual method from a base class, the abstract class can override the virtual method with an abstract method.
 
Some of the key points of abstract classes are:
  • A class may inherit only one abstract class.
  • Members of an abstract class may have any access modifier.
  • Abstract class methods may OR may not have an implementation.
  • Such a type of class cannot be instantiated but it allows the other classes to inherit from it, in other words from an abstract class.
  • Abstract classes allow definition of fields and constants.
Now let us see the abstract class with an example. Use the following procedure to create a console application:
  1. Open Visual Studio from Start - - All programs -- Microsoft Visual Studio.
  2. Then go to to "File" -> "New" -> "Project..." then select Visual C# -> Windows -> Console application.
  3. After that specify the name such as abstract class  or whatever name you wish and the location of the project and click on the OK button. The new project is created.
Add the namespace at the top of the program.cs class file, as in:
using System;
And use the following code in the program.cs class file:
abstract.png
Now run the application. The following output will be displayed:
ouput.png
Summary
In the preceding article ,I have briefly explained abstract classes to make them understandable to beginners and newcomers. If you have any suggestion regarding this article then please contact me.

Post a Comment

www.CodeNirvana.in

Protected by Copyscape
Copyright © Compilemode