I'm trying to make a parent class and child classes, lets say the parent class is called functionality and has functions like add()
, validate()
, and delete()
, and the child classes are driver and passenger , each of the child classes inherit the functions but needs extra parameters and different logic for each inherited function, should I define the function but leave it blank? how is this helpful apart from extendibility?, and should I define a different constructor for each child class because they have different extra variables?
class functionality
class functionality{
protected $from;
protected $to;
protected $date;
protected $name;
public function add(){
}
public function validate(){
}
public function delete(){
}
}
class driver
class driver extends functionality {
private $gasMoney
function add($from, $to, $date, $name, $gasMoney){
//some logic and adding to database
}
}
class passenger
class passenger extends functionality {
private $seatPrefrance
function add($from, $to, $date, $name, $seatPreferance){
//different logic than class driver and
}
}
is this an acceptable approach? and how would I define a constructer? should I define it in the parent class? does the child classes inherit it and can add more to it?
My Answer:
Inheritance in object-oriented programming allows child classes to inherit properties and methods from a parent class. In the scenario you described, it is not necessary to define empty functions in the parent class if the child classes will override those functions with their own implementation.
In your example, the `add()` function in the `functionality` class can be left empty, as the `driver` and `passenger` classes will provide their own implementation of the `add()` function with additional parameters and logic.
Regarding constructors, each child class can have its own constructor with additional parameters specific to that class. The parent class can also have its own constructor, which the child classes will inherit. If a child class needs to add additional parameters or logic to the constructor, it can do so by defining its own constructor.
Overall, the approach you have described is acceptable and follows the principles of object-oriented programming. It allows for code reusability, extensibility, and flexibility in defining different behaviors for each child class.
Rate this post
5 of 5 based on 4590 votesComments