Abstract classes and methods

1291 0

We use abstract classes and methods when we need to commit the child classes to certain methods that they inherit from the parent class but we cannot commit about the code that should be written inside the methods.

An abstract class is a class that has at least one abstract method. Abstract methods can only have names and arguments, and no other code. Thus, we cannot create objects out of abstract classes. Instead, we need to create child classes that add the code into the bodies of the methods, and use these child classes to create objects.

How to declare classes and methods as abstract?
In order to declare a class as abstract, we need to prefix the name of the class with the abstract keyword.
See the following example:

We put the abstract methods that are also declared with the abstract keyword within the abstract class. Abstract methods inside an abstract class don’t have a body, only a name and parameters inside parentheses.
In the example given below, we create a public abstract method, calcNumMilesOnFullTank(), that is the skeleton for methods that we will create in the child classes. Once created, these methods will return the number of miles a car can be driven on a full tank of gas.

It is important to know that once we have an abstract method in a class, the class must also be abstract.

Can we have non abstract methods inside an abstract class?
An abstract class can have non abstract methods. In fact, it can even have properties, and properties couldn’t be abstract.
Let’s add to our example the protected property, $tankVolume, and public method with the name of setTankVolume().


How to create child classes from an abstract class?

Since we cannot create objects from abstract classes, we need to create child classes that inherit the abstract class code. Child classes of abstract classes are formed with the help of the extends keyword, like any other child class. They are different in that they have to add the bodies to the abstract methods.
The child classes that inherit from abstract classes must add bodies to the abstract methods.
Let’s create a child class with the name of Honda, and define in it the abstract method that it inherited from the parent, calcNumMilesOnFullTank().

We can create another child class from the Car abstract class and call it Toyota, and here again define the abstract method calcNumMilesOnFullTank() with a slight change in the calculation. We will also add to the child class its own method with the name of getColor() that returns the string “beige”.

Let’s create a new object, $toyota1, with a full tank volume of 10 Gallons, and make it return the number of miles on full tank as well as the car’s color.

Result:
330
beige

In this article

Join the Conversation


Share