• Home
  • About
  • Contact
  • ado.net
  • angular
  • c#.net
  • design patterns
  • linq
  • mvc
  • .net core
    • .Net Core MVC
    • Blazor Tutorials
  • sql
  • web api
  • dotnet
    • SOLID Principles
    • Entity Framework
    • C#.NET Programs and Algorithms
  • Others
    • C# Interview Questions
    • SQL Server Questions
    • ASP.NET Questions
    • MVC Questions
    • Web API Questions
    • .Net Core Questions
    • Data Structures and Algorithms

Wednesday, November 22, 2017

What is Abstract Class and When we should use Abstract Class

 Abhishek Tomer     November 22, 2017     C#, Interview Question     No comments   

Hi friends! In our previous sessions we have seen Difference Between Class and Struct. And in our last session we learnt Usability of SecureString object in C#

Today, we are going to learn about some facts of Abstract Class in C#.Net.

So let's start with a question
Q. What is an Abstract Class? When and Why we should use it?
Ans. Answer to this question is here.

The abstract keyword enables you to create classes or class members that are incomplete and they must be implemented in a derived class.

Classes are declared as abstract by putting the keyword abstract before the class definition.
For example:
public abstract class A
{
    // Class members here.
}

Abstract classes may also contain abstract methods. This is also accomplished by adding the keyword abstract before the return type of the method.
For example:
public abstract class A
{
    public abstract void DoWork(int i);
}

Abstract class members have no implementation, so the class member 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.
If a virtual method is declared as abstract, it is still virtual to any class inheriting from the abstract class.
Here are some core points about Abstract Class, when and why we should Abstract Class?
  • We can create abstract class when we want to move common functionality into 2 or more related classes into a base class and prevent the developer to instantiated this class.
  • We can use code reusability and maintainability mechanism.
  • Easy to extent the code in feature.
Example: - Suppose for now we have two type of employee FullTimeEmployee and ContractEmployee and we want to display the FullName, MonthlySalary to user.

We can achieve this task with 3 approaches.
Let's use 1st approach - Using Separate classes

FullTimeEmployee
public class FullTimeEmployee
    {
        public int ID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string MobileNo { get; set; }
        public int AnualSalary { get; set; }

        public string getFullName()
        {
return this.FirstName + " " + this.LastName;
        }
        public int getSalary()
        {
         return this.AnualSalary / 12;
        }

    }
ContractEmployee:
public class ContractEmployee
    {
        public int ID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string MobileNo { get; set; }
        public int HourlyPay { get; set; }
        public int WorkedHour { get; set; }

        public string getFullName()
        {
 return this.FirstName + " " + this.LastName;
        }
        public int getSalary()
        {
    return this.HourlyPay * this.WorkedHour;
        }

    }
Implementation :
public class AbstractClassDemo
    {
        static void Main(string[] args)
        {
            //Full Time Employee
            FullTimeEmployee ftEmp = new FullTimeEmployee()
            {
                ID = 1,
                FirstName = "Tom",
                LastName = "Ken",
                MobileNo = "1345",
                AnualSalary = 144000

            };
            Console.WriteLine("Full Name: "+ftEmp.getFullName());
            Console.WriteLine("Salary : " + ftEmp.getSalary());

            //Contract Employee
            ContractEmployee cEmp = new ContractEmployee()
            {
                ID = 1,
                FirstName = "Pan",
                LastName = "Jan",
                MobileNo = "1345",
                HourlyPay = 200,
                WorkedHour=50
            };
            Console.WriteLine("Full Name: " + cEmp.getFullName());
            Console.WriteLine("Salary : " + cEmp.getSalary());

            Console.ReadKey();
        }
    }
Output:
Full Name= Tom Ken
Salary= 12000
Full Name=  Pam Jan
Salary=10000

Explanation:-
In this example we can see that it will display correct output. But above code have lot off problem like.

Problem:
1) Code duplicated: - like ID, FirstName, LastName, MobileNumber, GetFullName are same in both classes.
2) Code Maintainability and extensibility:- Suppose in feature organization want to display MiddleName so we need to add MiddleName on Both class and modify the GetFullName method on both class that take time.

Solution:
1) Make a base class and move the all common code into that base class. That resolve the duplicate code.
2) Inherit the base class into the both classes. That resolve the extensibility means we will added the MiddleName only base class if required.
Question: - Should we create an abstract class or Non-abstract class.
2nd Approach :  using Non-Abstract Class

BaseEmployee:
public class BaseEmployee
    {
        public int ID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string MobileNo { get; set; }

        public string getFullName()
        {
            return this.FirstName + " " + this.LastName;
        }
        //feature implementation
        public virtual int getSalary()
        {
           throw new NotImplementedException();
        }
    }
FullTimeEmployee
public class FullTimeEmployee: BaseEmployee
    {
        public int AnualSalary { get; set; }
        public override int getSalary()
        {
            return this.AnualSalary / 12;
        }
    }
ContractEmployee:
public class ContractEmployee:BaseEmployee
    {
        public int HourlyPay { get; set; }
        public int WorkedHour { get; set; }
        public override int getSalary()
        {
            return this.HourlyPay *this.WorkedHour;
        }
    }
Implementation:
public class AbstractClassDemo
    {
        static void Main(string[] args)
        {
            //Full Time Employee
            FullTimeEmployee ftEmp = new FullTimeEmployee()
            {
                ID = 1,
                FirstName = "Tom",
                LastName = "Ken",
                MobileNo = "1345",
                AnualSalary = 144000

            };
            Console.WriteLine("Full Name: "+ftEmp.getFullName());
            Console.WriteLine("Salary : " + ftEmp.getSalary());

            //Contract Employee
            ContractEmployee cEmp = new ContractEmployee()
            {
                ID = 1,
                FirstName = "Pan",
                LastName = "Jan",
                MobileNo = "1345",
                HourlyPay = 200,
                WorkedHour=50
            };
            Console.WriteLine("Full Name: " + cEmp.getFullName());
            Console.WriteLine("Salary : " + cEmp.getSalary());

            Console.ReadKey();
        }
    }

Output:-
Full Name=Tom Ken
Salary=12000
Full Name=Pam Jan
Salary=10000

Explanation:- 
Now we can see that by creating base class all the common code are reusable and maintainable and output is same as before. But have some problem.
Problem: A developer can easily able to create the instance of BaseEmployee class that is not good practice and also get a run time exception on those method that are not implemented like.
BaseEmployee baseEmp=new BaseEmployee();        //able to create instance of BaseEmployee
baseEmp.GetFullName();
baseEmp.GetSalary(); //this will throw an not implemented exception at run time.

Solution :
1) Make the BaseEmployee class as abstract. That prevent the instantiation.
2) Make the GetSalary() method as abstract. That force the drive class to be implemented this method.

Method-2 : using Abstract Class
BaseEmployee
 Public abstract class BaseEmployee
    {
        public int ID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string MobileNo { get; set; }

        public string getFullName()
        {
            return this.FirstName + " " + this.LastName;
        }
        //Implemented by drive class
        public abstractint getSalary()
    }

FullTimeEmployee
public class FullTimeEmployee: BaseEmployee
    {
        public int AnualSalary { get; set; }
        public override int getSalary()
        {
            return this.AnualSalary / 12;
        }
    }
ContractEmployee:
public class ContractEmployee:BaseEmployee
    {
        public int HourlyPay { get; set; }
        public int WorkedHour { get; set; }
        public override int getSalary()
        {
            return this.HourlyPay *this.WorkedHour;
        }
    }
Implementation:
public class AbstractClassDemo
    {
        static void Main(string[] args)
        {
            //Full Time Employee
            FullTimeEmployee ftEmp = new FullTimeEmployee()
            {
                ID = 1,
                FirstName = "Tom",
                LastName = "Ken",
                MobileNo = "1345",
                AnualSalary = 144000
            };
            Console.WriteLine("Full Name: "+ftEmp.getFullName());
            Console.WriteLine("Salary : " + ftEmp.getSalary());

            //Contract Employee
            ContractEmployee cEmp = new ContractEmployee()
            {
                ID = 1,
                FirstName = "Pan",
                LastName = "Jan",
                MobileNo = "1345",
                HourlyPay = 200,
                WorkedHour=50
            };
            Console.WriteLine("Full Name: " + cEmp.getFullName());
            Console.WriteLine("Salary : " + cEmp.getSalary());
            Console.ReadKey();
        }
    }

Output:- 
Full Name=Tom Ken
Salary=12000
Full Name=Pam Jan
Salary=10000

Explanation:- 
Now we can see that by creating base class as abstract and getSalary() as abstract method we can prevent developer to instantiated the BaseEmployee class and force drive class to implement the GetSalary() method.

Summary:
So, Guys this is all about Abstract Class.
I Hope in this post covered all the points about Abstract Class and its Advantages which will be helpful to re-collect in your memory and crack interview.

Please share this post with your friends and colleagues.
For any queries please post a comment below.

Happy Coding ðŸ˜‰
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Post Older Post

0 comments:

Post a Comment

If you like this website, please share with your friends on Facebook, Twitter, LinkedIn.

Join us on Telegram

Loved Our Blog Posts? Subscribe To Get Updates Directly To Your Inbox

Like us on Facebook

Popular Posts

  • What is Dependency Injection(DI)
    Hi friends! Today we are going to learn about Dependency Injection and in our last session we have come across Static classes and where it s...
  • C# Programming Examples on Sorting
    Today i am going to tell you some of the Sorting programming questions in C#. Q1- Write a C# program to perform Selection sort. Ans:  Sel...
  • Calling Web API Service in a Cross-Domain Using jQuery AJAX
    In this article, I am going to discuss Calling Web API Service in a Cross-Domain Using jQuery AJAX . Please read our previous article befor...
  • ViewBag in ASP.NET Core MVC
    In this article, I am going to discuss the use of ViewBag in ASP.NET Core MVC application with examples. Please read our previous article ...
  • Recursion And Back Tracking
    In this article, I am going to discuss Recursion And BackTracking in detail. Please read our previous article where we discussed Master Th...
  • What is Abstract Class and When we should use Abstract Class
    Hi friends! In our previous sessions we have seen  Difference Between Class and Struct . And in our last session  we learnt Usability of Sec...
  • Binary to Decimal Conversion in C# with Examples
    In this article, I am going to discuss the Binary to Decimal Conversion in C# with some examples. Please read our previous article where w...

Blog Archive

Contact Form

Name

Email *

Message *

Tags

.Net .Net Core .Net Core MVC Algorithm Angular Anonymous Types Asp.Net Asp.Net MVC Blazor C# Data Structure Database Design Patterns Entity Framework Entity Framework Core Filters Interview Question Management Studio Programming Programs SQL Server SSMS Web API

Copyright © C# Techtics | All Right Reserved.

Protected by Copyscape