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:

If I wanted to implement this in the code:

In these 2 classes, there is only 1 difference.

iPad calculates the price as follows:

Price = ManafacturingCost + CostToCompany + CostToResearch; 

Where the iPhone does as follows:

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

Second, move all common functionality in the base class: what differentiates iPhone from iPad is that the iPhone is lightweight & its hardware.


Now let's get into the real action: Start coding fellas.

First and foremost: BaseClass AppleBase:

public class AppleBase  
   {  
 public string Name { get; set; }  
 public double Price { get; set; }  
 public double ManafacturingCost { get; set; }  
 public double CostToCompany { get; set; }        
   } 

Now iPhone:

public class IPhone : AppleBase  
   {  
 public bool IsLightWeighted { get; set; }  
 public void SetPrice()  
       {  
           Price = ManafacturingCost + CostToCompany;  
           Console.WriteLine("Price:     " + Price + System.Environment.NewLine);  
       }  
 public void SetHardware()  
       {  
           Console.WriteLine("Processor: Apple A13 Bionic" + System.Environment.NewLine  
                            + "Display:   6.1 inches:" + System.Environment.NewLine  
                            + "Ram:       4 GB");  
       }  
   } 

class iPad:

class IPad: AppleBase  
   {  
 public double CostToResearch { get; set; }  
 public void SetPrice()  
       {  
           Price = ManafacturingCost + CostToCompany + CostToResearch;  
           Console.WriteLine("Price:     " + Price + System.Environment.NewLine);  
       }  
 
 public void SetHardware()  
       {  
           Console.WriteLine("Processor: Apple A12X Bionic" + System.Environment.NewLine  
                            + "Display:   12.90 inches:" + System.Environment.NewLine  
                            + "Ram:       6 GB");  
       }  
   } 


Now the boss, the Main method:


class Program  
   {  
 static void Main(string[] args)  
       {  
           Console.WriteLine("---------------- IPhone -------------------");  
           IPhone iphone11 = new IPhone()  
           {  
               Name = "IPhone 11",  
               CostToCompany = 20000,  
               ManafacturingCost = 25000,  
               IsLightWeighted = true,  
           };  
           Console.WriteLine("Name:      " + iphone11.Name + System.Environment.NewLine);  
           iphone11.SetHardware();  
           iphone11.SetPrice(); 



           Console.WriteLine("---------------- IPad -------------------");  
           IPad ipadPro = new IPad()  
           {  
               Name = "IPad Pro",  
               CostToCompany = 20000,  
               ManafacturingCost = 35000,  
               CostToResearch = 10000  
           };  
           Console.WriteLine("Name:      " + ipadPro.Name + System.Environment.NewLine);  
           ipadPro.SetHardware();  
           ipadPro.SetPrice();  
       }  
   } 


Pretty good, now let's run this program.


It works but it is not perfect! There is still room for improvement. As a developer, I might do this:

public class AppleBase  
   {  
 public string Name { get; set; }  
 public double Price { get; set; }  
 public double ManafacturingCost { get; set; }  
 public double CostToCompany { get; set; }  
 public void SetPrice()  
       {  
 throw new NotImplementedException();  
       }  
   } 


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.

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.


public abstract class AppleBase 
{  
 public string Name { get; set; }  
 public double Price { get; set; }  
 public double ManafacturingCost { get; set; }  
 public double CostToCompany { get; set; }  
 public abstract void SetPrice();  
  } 

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

public override void SetPrice()  
      {  
          Price = ManafacturingCost + CostToCompany + CostToResearch;  
          Console.WriteLine("Price:     " + Price + System.Environment.NewLine);  
      } 

class iPhone


public override void SetPrice()  
      {  
          Price = ManafacturingCost + CostToCompany;  
          Console.WriteLine("Price:     " + Price + System.Environment.NewLine);  
      } 


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.

public abstract class AppleBase  
   {  
 public string Name { get; set; }  
 public double Price { get; set; }  
 public double ManafacturingCost { get; set; }  
 public double CostToCompany { get; set; }  
 public virtual void SetPrice() { }  
   } 

There is no change for IPad or IPhone classes, as they need the SetPrice method, but MacBook doesn't need to SetPrice.

class MacBook : AppleBase  
    {  
 public string Name { get; set; }  
 public void SetHardware()  
        {  
            Console.WriteLine("Processor: Apple A13 Bionic" + System.Environment.NewLine  
                             + "Display:   16 inches:" + System.Environment.NewLine  
                             + "Ram:       8 GB");  
        }  
    } 

Now let's see the overall output:


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.


Source: Paper.li