Purpose Of Abstract Class In Object Oriented Programming

Introduction


Hey there, greetings to you! I trust you are doing good.
 
In accordance with today's topic let's take a deep dive to find out the purpose of Abstract class in OOPS.
 
Let's go back to our old example of Apple.
 
Apple makes iPhones & iPads. These 2 classes share a lot of common properties still they are quite differentiable. Perfect! we need something like this to understand the behavior of an abstract class.
 
Let's say we are a noob programmer. As a noob programmer, we will create 2 classes, each for iPhone & iPad
 
Let us have a look at their UML:
 
Purpose Of Abstract Class In Object Oriented Programming
 
If I wanted to implement this in the code:
 
Purpose Of Abstract Class In Object Oriented Programming
 
In these 2 classes, there is only 1 difference.
 
iPad calculates the price as follows:
  1. Price = ManafacturingCost + CostToCompany + CostToResearch; 
 Where the iPhone does as follows:
  1. Price = ManafacturingCost + CostToCompany; 
Now, are we that dumb to make 2 different classes when they have so many things in common?
 
Of course not.
 
First, let's create a base class that will be inherited by IPhone & IPad.
 
Purpose Of Abstract Class In Object Oriented Programming
 
Second, move all common functionality in the base class: what differentiates iPhone from iPad is that the iPhone is lightweight & its hardware.
Purpose Of Abstract Class In Object Oriented Programming
Now let's get into the real action: Start coding fellas.
 
First and foremost: BaseClass AppleBase:
  1. public class AppleBase  
  2.    {  
  3.        public string Name { getset; }  
  4.        public double Price { getset; }  
  5.        public double ManafacturingCost { getset; }  
  6.        public double CostToCompany { getset; }        
  7.    } 
Now iPhone:
  1. public class IPhone : AppleBase  
  2.    {  
  3.        public bool IsLightWeighted { getset; }  
  4.        public void SetPrice()  
  5.        {  
  6.            Price = ManafacturingCost + CostToCompany;  
  7.            Console.WriteLine("Price:     " + Price + System.Environment.NewLine);  
  8.        }  
  9.        public void SetHardware()  
  10.        {  
  11.            Console.WriteLine("Processor: Apple A13 Bionic" + System.Environment.NewLine  
  12.                             + "Display:   6.1 inches:" + System.Environment.NewLine  
  13.                             + "Ram:       4 GB");  
  14.        }  
  15.    } 
 class iPad:
  1. class IPad: AppleBase  
  2.    {  
  3.        public double CostToResearch { getset; }  
  4.        public void SetPrice()  
  5.        {  
  6.            Price = ManafacturingCost + CostToCompany + CostToResearch;  
  7.            Console.WriteLine("Price:     " + Price + System.Environment.NewLine);  
  8.        }  
  9.   
  10.        public void SetHardware()  
  11.        {  
  12.            Console.WriteLine("Processor: Apple A12X Bionic" + System.Environment.NewLine  
  13.                             + "Display:   12.90 inches:" + System.Environment.NewLine  
  14.                             + "Ram:       6 GB");  
  15.        }  
  16.    } 
Now the boss, the Main method:
  1. class Program  
  2.    {  
  3.        static void Main(string[] args)  
  4.        {  
  5.            Console.WriteLine("---------------- IPhone -------------------");  
  6.            IPhone iphone11 = new IPhone()  
  7.            {  
  8.                Name = "IPhone 11",  
  9.                CostToCompany = 20000,  
  10.                ManafacturingCost = 25000,  
  11.                IsLightWeighted = true,  
  12.            };  
  13.            Console.WriteLine("Name:      " + iphone11.Name + System.Environment.NewLine);  
  14.            iphone11.SetHardware();  
  15.            iphone11.SetPrice(); 

  16.            Console.WriteLine("---------------- IPad -------------------");  
  17.            IPad ipadPro = new IPad()  
  18.            {  
  19.                Name = "IPad Pro",  
  20.                CostToCompany = 20000,  
  21.                ManafacturingCost = 35000,  
  22.                CostToResearch = 10000  
  23.            };  
  24.            Console.WriteLine("Name:      " + ipadPro.Name + System.Environment.NewLine);  
  25.            ipadPro.SetHardware();  
  26.            ipadPro.SetPrice();  
  27.        }  
  28.    } 
Pretty good, now let's run this program.
 
Purpose Of Abstract Class In Object Oriented Programming
 
It works but it is not perfect! There is still room for improvement. As a developer, I might do this:
  1. public class AppleBase  
  2.    {  
  3.        public string Name { getset; }  
  4.        public double Price { getset; }  
  5.        public double ManafacturingCost { getset; }  
  6.        public double CostToCompany { getset; }  
  7.        public void SetPrice()  
  8.        {  
  9.            throw new NotImplementedException();  
  10.        }  
  11.    } 
What is the problem? I have defined the SetPrice method in AppleBase. But fellas AppleBase is not a product, it doesn't have a product to set a price.
 
Get it? It is a concept. It is abstract in nature and it doesn't exist. Whoever implements this abstraction has the power of bringing it to life.
 
Like out concrete classes iPad & iPhone did with AppleBase class.
 
Therefore, we have to declare our AppleBase class abstract so that developers can avoid the mistake of initializing the abstract class.
 
Because abstract classes can not be instantiated you will get a compile-time error.
 
Purpose Of Abstract Class In Object Oriented Programming
 
Now that we have made our base class abstract, we can take advantage of it. We know that Apple will never sell an iPad or iPhone for free. This makes SetPrice method soul these 2 classes. So we can move SetPrice to AppleBase class and declare it abstract. This will force the iPhone & iPad to define their price.
  1. public abstract class AppleBase 
  2. {  
  3.       public string Name { getset; }  
  4.       public double Price { getset; }  
  5.       public double ManafacturingCost { getset; }  
  6.       public double CostToCompany { getset; }  
  7.       public abstract void SetPrice();  
  8.   } 
We have to use the Override keyword in the iPhone & iPad classes because now the SetPrice method belongs to AppleBase class and derived classes are overriding it.
 
override
 
This modifier is used with the derived class method. It is used to modify a virtual or abstract method of a base class.
 
class iPad
  1. public override void SetPrice()  
  2.       {  
  3.           Price = ManafacturingCost + CostToCompany + CostToResearch;  
  4.           Console.WriteLine("Price:     " + Price + System.Environment.NewLine);  
  5.       } 
class iPhone
  1. public override void SetPrice()  
  2.       {  
  3.           Price = ManafacturingCost + CostToCompany;  
  4.           Console.WriteLine("Price:     " + Price + System.Environment.NewLine);  
  5.       } 
Now let's say Apple decided to have a new product line say MacBook. here while creating a MacBook's class we don't have to define all the common properties.
 
We can directly inherit them from the AppleBase class and be done with it.
 
Now there is a twist. Apple actually decided to distribute these MacBooks for free. But wait we have forced AppleBase to define a price for all of its derived classes.
 
This means the MacBook has to define the price. Now what. Worry not. You can simply use virtual keyword in SetPrice Method:
 
virtual
 
This modifier is used within the base class method. It is used to modify a method in the base class which is going to be overridden in the derived class. It does not force the method to be overridden. It is up to derived class if it wants to override a virtual method or not.
  1. public abstract class AppleBase  
  2.    {  
  3.        public string Name { getset; }  
  4.        public double Price { getset; }  
  5.        public double ManafacturingCost { getset; }  
  6.        public double CostToCompany { getset; }  
  7.        public virtual void SetPrice() { }  
  8.    } 
There is no change for IPad or IPhone classes, as they need the SetPrice method, but MacBook doesn't need to SetPrice.
  1. class MacBook : AppleBase  
  2.     {  
  3.         public string Name { getset; }  
  4.         public void SetHardware()  
  5.         {  
  6.             Console.WriteLine("Processor: Apple A13 Bionic" + System.Environment.NewLine  
  7.                              + "Display:   16 inches:" + System.Environment.NewLine  
  8.                              + "Ram:       8 GB");  
  9.         }  
  10.     } 
Now let's see the overall output:
 
Purpose Of Abstract Class In Object Oriented Programming
 
See Macbook is not defining any price where the other 2 products are.
 
There are some restrictions when we use the abstract class.
  • Override keyword is necessary if we wish to use the base class method.
  • An abstract class can not be declared static.
  • You can't instantiate an abstract class.
  • If class A has an abstract method, then class A has to be declared abstract as well.

    • But an abstract class may or may not have an abstract method.

  • If a derived class fails to define all the abstract methods of base class then derived class has to be declared abstract as well.

Conclusion

 
In this article, we learned how to reuse code,
 
How to write extensible code, that if future requirements change then we can make changes without touching existing logic.
 
When to use abstract class & how to use an abstract class.
 
What are abstract & virtual modifiers and when to use them.
 
This was a good session. Thanks for being part of this article. 
 
I believe you have a grasp on some insights over abstract class in object-oriented programming.
 
I wish you all the very best. Please apply them when necessary.
 
If you wish to connect with me, find me @
As always, Happy Coding!


Recommended Free Ebook
Similar Articles