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:
- Open Visual Studio from Start - - All programs -- Microsoft Visual Studio.
- Then go to to "File" -> "New" -> "Project..." then select Visual C# -> Windows -> Console application.
- 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;
Now run the application. The following output will be displayed:
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