Abstract class declared inside namespace should be either public or internal hence below code will throw compilation error.
- using System;
- namespace ConsoleApplication3
- {
- private abstract class AbstractClass
- {}
- }
Abstract classes can’t be instantiated hence if you try to execute below code it will throw compilation error.
- using System;
- namespace ConsoleApplication3
- {
- public abstract class AbstractClass
- {}
- class DeriveAbstract : AbstractClass
- {
- AbstractClass abstract_class = new AbstractClass();
- }
- }
Abstract class constructors are called when we create instance of derive class and they are called before derive class constructor.
- using System;
- namespace ConsoleApplication3
- {
- public abstract class AbstractClass
- {
- protected AbstractClass()
- {
- Console.WriteLine("protected abstract class constructor");
- }
- }
- class DeriveAbstract : AbstractClass
- {
- protected DeriveAbstract()
- {
- Console.WriteLine("Public derive class constructor");
- }
- static void Main(string[] args)
- {
- DeriveAbstract deriveclass = new DeriveAbstract();
- }
- }
- }
No point in creating private constructor inside an abstract class as we can’t even use it inside the derive class. Even creating public constructor inside abstract class doesn’t make sense hence protected access modifier is preferred.
Abstract methods or properties can’t be private and the derive class should implement all the abstract methods and properties using the override keyword.
- using System;
- namespace ConsoleApplication3
- {
- public abstract class AbstractClass
- {
- private string name;
- public string Name
- {
- get
- {
- return this.name;
- }
- set
- {
- value = this.name;
- }
- }
- protected abstract string Salary { get; set; }
- public void DisplayName(string name)
- {
- Console.WriteLine("Name Entered is : {0}", name);
- }
- protected abstract void DisplayTotalSalary(long salary);
- }
- class DeriveAbstract : AbstractClass
- {
- private string salary;
- protected override string Salary
- {
- get
- {
- return this.salary;
- }
- set
- {
- value = this.salary;
- }
- }
- protected override void DisplayTotalSalary(long salary)
- {
- long totalSalary = salary * 12;
- Console.WriteLine("Total salary : {0}", totalSalary);
- }
- static void Main(string[] args)
- {
- DeriveAbstract deriveclass = new DeriveAbstract();
- deriveclass.DisplayName("Elima Tripathy");
- deriveclass.DisplayTotalSalary(50000);
- }
- }
- }
As per MSDN the purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share.
For example, a class library may define an abstract class that is used as a parameter to many of its functions, and require programmers using that library to provide their own implementation of the class by creating a derived class.