C# abstract classes offer a robust way to establish a blueprint for other classes, ensuring that methods must be implemented by offering shared code. These classes are utilized when there is a necessity to establish a universal pattern for a group of classes, enabling subclasses to define specific methods or properties. They are commonly employed to outline a fundamental structure or functionality shared among multiple subclasses while still permitting these subclasses to introduce their unique implementations.
In C#, an abstract class is a class defined as abstract, allowing a mix of abstract and concrete methods within it. The class encompasses various fields, constructors, and methods, yet it cannot be directly instantiated. Subclasses are obligated to furnish implementations for all abstract methods within the abstract class.
Syntax
It has the following syntax:
abstract class ClassName
{
// Abstract method (no body)
public abstract return_type MethodName(parameters);
// Normal method (with body)
public return_type NormalMethod(parameters)
{
// implementation
}
}
In this syntax,
- abstract class ClassName: It represents the name of the abstract class, which means that it cannot be instantiated directly.
- return_type: It represents the return type of the abstract method.
- NormalMethod: It represents the body that performed the implementation.
C# Abstract Class Example
Let's consider a scenario to demonstrate the concept of an abstract class in the C# programming language.
Example
using System;
public abstract class Shape
{
public abstract void draw();
}
public class Rectangle : Shape
{
public override void draw()
{
Console.WriteLine("drawing rectangle...");
}
}
public class Circle : Shape
{
public override void draw()
{
Console.WriteLine("drawing circle...");
}
}
public class TestAbstract
{
public static void Main()
{
Shape s;
s = new Rectangle();
s.draw();
s = new Circle();
s.draw();
}
}
Output:
drawing rectangle...
drawing circle...
Explanation:
In this illustration, we define an abstract class named Shape containing an abstract function called draw. Following this, we introduce the Rectangle and Circle subclasses that inherit from Shape and provide implementations for their draw methods. Within the main function, a Shape reference is employed to invoke the draw function on instances of both Rectangle and Circle, displaying their individual output messages.
C# Abstract Class Example with Constructors for Initialization
Let's consider a different instance to demonstrate abstract classes in C# involving Constructors.
Example
using System;
abstract class Employee
{
public string Name { get; set; }
public double Salary { get; set; }
public abstract void EmpName();
public void EmpSalary()
{
Console.WriteLine($"Salary: {Salary}");
}
}
class Emp1 : Employee
{
public Emp1()
{
Name = "Johnson";
Salary = 25000;
}
public override void EmpName()
{
Console.WriteLine($"Name: {Name}");
}
}
class Emp2 : Employee
{
public Emp2()
{
Name = "Michael";
Salary = 30000;
}
public override void EmpName()
{
Console.WriteLine($"Name: {Name}");
}
}
class C# Tutorial
{
static void Main(string[] args)
{
Employee emp1 = new Emp1();
emp1.EmpName();
emp1.EmpSalary();
Employee emp2 = new Emp2();
emp2.EmpName();
emp2.EmpSalary();
}
}
Output:
Name: Johnson
Salary: 25000
Name: Michael
Salary: 30000
Explanation:
In this instance, we've created a class named Employee that serves as a foundational class, encompassing various shared attributes and procedures. Following this, we introduce two subclasses, Emp1 and Emp2, which assign distinct names and salaries through constructors and redefine the abstract method EmpName. During execution, all employee details are exhibited, showcasing the collective generic features of abstract classes alongside tailored implementations.
Abstract Method
A method that is defined as abstract and lacks an implementation is referred to as an abstract method. Abstract methods are exclusively declared within abstract classes and must be implemented by subclasses.
Syntax:
It has the following syntax:
access-modifier abstract return-type MethodName(parameters);
In this syntax,
- Access-modifier: It represents the visibility of the abstract method.
- Abstract: It is used to define the method as abstract.
- Return-type: It is used to define the data type that the method should return.
- MethodName: It represents the abstract method name.
An abstract method within C# functions as a virtual method internally, enabling it to be replaced by the subclass. It is not permissible to include static and virtual keywords in the declaration of an abstract method.
C# Abstract Method Example
Let's consider an example to demonstrate the concept of an abstract method in C#.
Example
using System;
abstract class Animal
{
public abstract void Speak();
public abstract void Drink();
}
class Cat : Animal
{
public override void Speak()
{
Console.WriteLine("Cat says: Meow! Meow!");
}
public override void Drink()
{
Console.WriteLine("Cat is drinking milk.");
}
}
class C# Tutorial
{
static void Main()
{
Animal myCat = new Cat();
myCat.Speak();
myCat.Drink();
}
}
Output:
Cat says: Meow! Meow!
Cat is drinking milk.
Explanation:
In this example, we take an abstract class Animal with two abstract methods Speak and Drink, which has no body. After that, the Cat class is inherited from Animal and overrides both methods with its implementation. In the main function, an Animal reference is used to a Cat object, and invoking Speak and Drink invokes the overridden methods, which demonstrate the Cat's behavior.
C# Abstract Method Example for Bank Account Details
Let's consider a scenario to demonstrate the concept of abstract method for managing Bank Account Details in C#.
Example
using System;
abstract class BankAcc
{
public string AccHolder { get; set; }
public double Balance { get; protected set; }
// using Abstract methods
public abstract void Deposit(double amount);
public abstract void Withdraw(double amount);
}
class SavingsAcc : BankAcc
{
public SavingsAcc(string holder, double initialBal)
{
AccHolder = holder;
Balance = initialBal;
}
public override void Deposit(double amount)
{
Balance += amount;
Console.WriteLine($"{amount}Rs deposited in Savings Account.");
}
public override void Withdraw(double amount)
{
if (Balance >= amount)
{
Balance -= amount;
Console.WriteLine($"{amount}Rs withdrawn from Savings Account.");
}
else
{
Console.WriteLine("Insufficient balance.");
}
}
}
class C# Tutorial
{
static void Main(string[] args)
{
BankAcc acc = new SavingsAcc("Robert", 1800);
acc.Deposit(600); // Calls overridden Deposit
acc.Withdraw(300); // Calls overridden Withdraw
Console.WriteLine($"Total Balance: {acc.Balance}");
}
}
Output:
600Rs deposited in Savings Account.
300Rs withdrawn from Savings Account.
Total Balance: 2100
Explanation:
In this illustration, we are examining an abstract class that establishes the framework for a bank account, featuring two abstract procedures: Deposit and Withdraw. Subsequently, we introduce a derived class SavingsAcc, which furnishes specific implementations of these procedures to manage deposit and withdrawal operations. Within the primary method, we instantiate an object of the SavingsAcc class, perform transactions, and exhibit the revised account balance.
Usage of Abstract Class in C#
Several uses of abstract class in C# are as follows:
- We can create multiple versions of the component because versioning is not a problem when dealing with abstract classes.
- We can add properties or methods to an abstract class without recompiling, and all the inheriting classes are updated with the change automatically.
- It is required to supply default behaviors along with general behaviors that several derived classes will have in common and be able to override.
Difference between Abstract Class and Interface
There exist various key distinctions between an Abstract Class and an Interface in C#. The primary variances include:
| Features | Abstract Class | Interface |
|---|---|---|
| Definition | Abstract class is a partially implemented class that defines both what and how a class should perform operations. | An interface is a contract that defines only method signatures, properties, events, and indexers, but it has no implementation. |
| Instantiation | It cannot be instantiated. | It cannot be instantiated. |
| Access Modifiers | It uses all access modifiers. | It doesn't use an access modifier because all classes are public by default. |
| Members | It contains several fields, constructors, and methods. | It contains only method signatures, events, properties, and indexers. |
| Inheritance | It uses only single inheritance. | It can implement multiple inheritance. |
| Implementation | It can provide a default implementation. | It has no implementation. |
Benefits of Abstract Class in C#
There are several benefits of the abstract class in C#. Some of them are as follows:
- Promotes code reusability: Abstract classes enable us to specify common behavior, methods, and properties that may be shared by many derived classes.
- Acts as a template for derived classes: These are a template or blueprint for derived classes.
- Supports inheritance and polymorphism: Abstract classes allow polymorphism so that derived classes can be viewed as instances of the abstract class.
- Specifies contracts using abstract methods: Abstract classes specify contracts using abstract methods, which are implemented by derived classes.
- Supports code modularization and organization: Abstract classes allow code to be organized and support modularity.
- Allows extensibility in the future: Abstract classes are meant to be extended by derived classes.
Disadvantages of Abstract Class in C#
There are several disadvantages of the abstract class in C#. Some of them are as follows:
- Tight coupling: Abstract classes introduce an element of coupling between the base abstract class and its subclasses. It suggests that changes to the abstract class could impact all subclasses.
- Incomplete implementation: Abstract classes usually contain abstract methods, which need to be implemented in their derived classes.
- Limited flexibility: When an abstract class is declared, its struct and contracts become more rigid than those of interfaces.
- Object-oriented design issues: In certain situations, abstract classes can break some of the principles of object-oriented design, including the Single Responsibility Principle (SRP) or the Interface Segregation Principle (ISP).
Conclusion
In summary, the abstract class in C# acts as a foundational blueprint that can include fully implemented elements as well as abstract elements without implementations. Derived classes must provide implementations for the abstract elements. Direct instantiation of abstract classes is not permitted, making them well-suited for offering shared functionality and enforcing the implementation of specific methods in subclasses.
Abstract Class FAQs
1) Can an abstract class contain constructors?
Yes, constructors can be included in an abstract class. They get called when an instance of a subclass is generated in order to set up the properties of the base class.
An abstract class can indeed include non-abstract members.
Yes, it can contain both theoretical (without implementation) and practical (with implementation) elements. This enables a combination of shared implementation and mandatory overrides.
3) What are the scenarios where Abstract Classes are more suitable than Interfaces?
Abstract classes are employed to incorporate shared functionality or offer a foundational version that can be expanded upon by subclasses. In contrast, interfaces serve the purpose of outlining a set of requirements for functionality without specifying any implementation details.
4) Is it possible to create an instance of an abstract class?
No, it is not possible to instantiate an abstract class directly. Instances can only be created for classes that inherit from the abstract class and provide implementations for all its abstract members.
5) How do an interface and an abstract class differ in C#?
The primary contrast between an interface and an abstract class in C# can be summarized as:
An abstract class can consist of both concrete and abstract elements, supports fields, and permits the use of access modifiers.
Interface: It consists solely of declarations, devoid of any fields, and all its members are inherently public.