It is common to identify situations where an object can have more than one common feature. For example, a beer. Our example may seem unusual, but it will help us for illustration and understanding. Before actually be a beer, it is a drink and can also be a recipe ingredient. Many recipes take beers and that it can also be classified as an ingredient. Analyzing this scenario is that we will explain following the concept of multiple inheritance in object-oriented programming.
A beer has specific characteristics such as white collar and a yellowish or darker color. It is also a drink which in many cases must be stored in a special way. She is also a type of ingredient, since in cuisine it is very common to use the beer in dishes that take meat and special sauces.
Bringing this scenario for the programming codes, how could a “beer” class have drink attributes and ingredient attributes at the same time? To solve this problem, you must then apply the concept of multiple inheritance. Check out the following example:
class Drink{
$type;
public function setType($var) {
$type = $var;
}
}
class Ingredient{
$quantity;
$recipename;
public function setQuantity ($qt) {
$ qtde = $qt;
}
public function setRecipeName($name) {
$ recipename = $name;
}
}
class Beer extends Beer, Ingredient{
}
$beer = new Beer;
$beer. setTypo(“Pilsen”);
$beer. setRecipeName(“Beer Sauce”);
$beer. setQuantity (“2 cups”);
The syntax used to apply the class inheritance is also used to assign one or more classes, separated by commas. The behavior is also the same, from the descendant class it is possible to call the parent class objects. In the example, the beer type is indicated using the setType () method. On the other hand, the amount that will be used in the indicated recipe, is set using the setQuantity () method. Every mentioned method was implemented in a different class.
This dynamism in the use of the concept of heritage optimizes production, ensures the ultimate in code reuse and centralizes the control of the information, as a generic class can be used in several classes descendants.
Check out more content on our blog!
Learn all about Scriptcase.
You might also like…