2Hats . 2 minutes

Simple explanation of abstract classes and why we would use them

Lets consider an example. We are creating 2 classes for employees in an office. There are 2 kinds of employees, fulltime and contract employees.
Both type of employees have some common methods and properties like, name, monthly salary etc.

For the contract employee, there are common properties like first name, last name and there is also the method called getFullName. But there is a difference in the way monthly payment is calculated for contract employees. Its hourly pay multiplied by total hours worked in that month.

This works alright but what if we want to add a method called middle name? We would have to add it to both the EmployeeContract and EmployeeFulltime classes.

Instead of doing this, we could copy the common properties and methods to a base class like so.

Then we could extend our EmployeeContract and EmployeeFulltime classes with the EmployeeBase class and take out all the common methods and properties from them.

So if we want to add a common method called getMiddleName, we could just do that in the base class.

But we still have couple of problems here.
1. The developers who use your base class can do this:
$base = new EmployeeBase(array(‘firstName’=>’John’,’lastName’=>’Doe’));
We don’t need them to use our base class like this, there is no employee called a base employee and it doesn’t make sense.

2. We need all child classes to have a getMonthlyPayment method because its mandatory that all employees have a monthly payment. There is no guarentee that the
developer will be creating that method.

An abstract base class would solve both the above issues.

1. An abstract class cannot be instantiated. It is only intended to be extended by child classes. If you try to extend it, it will throw an error.
2. getFullName is defined as an abstract method. So, it is mandatory for all child classes to have a method called getFullName.

Here is the updated base class as an abstract class.

blog
Greetings! I'm Aneesh Sreedharan, CEO of 2Hats Logic Solutions. At 2Hats Logic Solutions, we are dedicated to providing technical expertise and resolving your concerns in the world of technology. Our blog page serves as a resource where we share insights and experiences, offering valuable perspectives on your queries.
Aneesh ceo
Aneesh Sreedharan
Founder & CEO, 2Hats Logic Solutions
Subscribe to our Newsletter
Arsha Contact

    Stay In The Loop!

    Subscribe to our newsletter and learn about the latest digital trends.