Objective
Beside Inheritance which has provides a lot of benefit, in C# we can also provided with abstract class and interface. This tutorial will show you with the definition and how to use them to make your program more flexible.
Let's go
Abstract classes
There are times when you need to provide derived classes with a standard implementation and need to guarantee that a derived class provides an implementation for a particular property or method, or simply makes sense to have a class that can have no instances By declaring a class as abstract, you prevent it from being instantiated directly. As a result, abstract classes typically have protected constructor rather than public ones. If you don’t provide a default constructor, the compiler creates a protected default constructor for you. An abstract class can contain virtual, non-virtual and abstract members (known as methods). You need to note that:
public abstract class Vehicle { int wheels; protected Vehicle() {} public Vehicle(int wheels) { this.wheels = wheels; } /* * this class abstract member of the abstract class */ public abstract void Operate(); public void increaseSpeed(int v) { speed += v; } /* * this is virtual member that the derived class can optionally choose to override * to change the operation */ public virtual void decreaseSpeed(int v) { speed -= v; } } public class Car : Vehicle { /* * this class implements an abstract member from abstract class */ public override void Operate() { Console.WriteLine("this is implement member"); } /* * this class member overrides the virtual member of base class. */ public override void decreaseSpeed(int v) { speed -= v / 2; } };
Eplanation
In the above example, we declared an abstract Vehicle class. In this class, this class has three functions/members:
If the derived class is also abstract, id does not need to override a base class abstract member. Because an abstract member has no implementation until overridden in a derived class, it is not possible for that overridden member to call the same member form the base class.
Summary
In this tutorial we have show you about Abstract class definition, includes: