Wednesday, November 28, 2018

abstract method and abstract class

abstract method and abstract class


Summary: in this tutorial, you will learn about the PHP abstract class and abstract method, and learn how to use abstract class to define a framework for the class hierarchy.

Introduction to abstract method and abstract class

In an inheritance hierarchy, subclasses implement specific details, whereas the parent class defines the framework its subclasses. The parent class also serves a template for common methods that will be implemented by its subclasses. To make the parent classes more general and abstract, PHP provides abstract method and abstract class.
An abstract method is a method that do not have implementation. In order to create an abstract method, you use the abstract keyword as follows:
An abstract class is a class that contains at least one abstract method. To declare an abstract class, you also use the abstract keyword as follows:

PHP abstract class example

Let’s take a look at an example to understand how abstract class and abstract method work. We will develop new classes based on the following class diagram:

PHP Abstract Class Example
An abstract class cannot be instantiated. In other words, it is not allowed to create a new instance of an abstract class e.g., the following code is not allowed:
An abstract class can contain properties e.g., $firstname and $lastname.
An abstract class can contain methods that are fully implemented e.g. __toString() method.
The abstract class allows you to declare a class that has a partial implementation. The subclasses will provide specific implementation for abstract methods.
The classes that inherit an abstract class are called concrete classes, e.g., Employee class and Contractor class are concrete classes.
The following illustrates how to use the Employee class:
We can develop another concrete class named Contractor as follows:
And the sample code that uses the Contractor class:

No comments:

Post a Comment

form validation

function formsubmit ( ) { var empname = document .getElementById ( 'emp_name' ). value ; var email = document .getElem...