Practical Implementation Of Abstract Class
Lets talk about the practical implementation of the abstract class. Most people are very much aware about the theory of the these classes but as far as implementation is concerned, they are not sure about it.
Abstract class implementation
- public abstract class DataSource
- {
- protected string dataSourceName;
- private string environment;
- protected DataSource(string environment, string dsName) {
- this.environment = environment;
- this.dataSourceName = dsName;
- GetDataSourceCredentials();
- }
- private void GetDataSourceCredentials() {
- Console.WriteLine(string.Format("Get {0}'s connection setting for {1} environment from config file", dataSourceName, environment));
- }
- public abstract void OpenAndReturnConnection();
- }
- public class MsSqlDataSource: DataSource {
- public MsSqlDataSource(string environment): base(environment, "MsSQL") {}
- public override void OpenAndReturnConnection() {
- Console.WriteLine(string.Format("Create and return Connection for {0} dataSource", dataSourceName));
- }
- }
- public class OracleDataSource: DataSource {
- public OracleDataSource(string environment): base(environment, "Oracle") {}
- public override void OpenAndReturnConnection() {
- Console.WriteLine(string.Format("Create and return Connection for {0} dataSource", dataSourceName));
- }
- }
We should be aware that an abstract class can have its implementation for the methods. In the code, given above, I have created an abstract base class, named DataSource
. This class is derived to the concrete classes i.e. sSqlDataSource and OracleDataSource.
The concrete class will have its way to open the connection. There should be a common way to get the connection string for config file.
In our Application, there can be a chance that we have to use different data sources like Ms SQL server, Oracle server or maybe MS Excel file. In the code, mentioned above, I have a private method for getting the datasource connection string from the config file, based on the data source name and environment (e.g. DEV, QA or PROD).
Now, if you execute the code, given below:
- DataSource sqlDS = new MsSqlDataSource("DEV");
- sqlDS.OpenAndReturnConnection();
I will get the following output:
Here, I am getting the connection string for DEV environment. This functionality is common for all the classes derived from DataSource class. The creation of connection is specific to the derived class. Therefore, we have an abstract method in abstract base class.
Though, it is a very basic and small example but it can help you to understand the use of an abstract class.
Conclusion
In this article, I have discussed about the abstract class and its differences with an interface. The article also includes a small example , which makes you understand about the abstract class.