Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OOP abstract classes when to implement abstract methods

I'm trying to learn OOP in PHP, for now i have reached the abstract classes.

I have some problems understanding when should I implement abstract methods in the abstract class and when I should not.

For example, have this code:

<?php

abstract class concept_car {
    /**
     * Properties can not be declared as abstract natively:
     * http://stackoverflow.com/questions/7634970/php-abstract-properties
     */
    protected $weelNum  = NULL;
    protected $doorsNum = NULL;
    protected $color    = NULL;
    protected $carType  = NULL;
    // the inheritance class must define this methods
    abstract public function setWeelNum($weelNum);

    abstract public function setDoorsNum($doorsNum);

    abstract public function setCarType($carType);
}

I do not know if it is OK to declare the 3 methods as abstract or should I remove the abstract and implement them because the properties are in the same class as the methods.

In the actual form of the code I was thinking that I must declare the methods as abstract here and implement them in the inheritance class, in the child class, but I don't know if this is the correct way.

P.S: I am a beginner and I am trying to understand how things go, I didn't reach at design patterns yet so please explain me in concepts so i can know what is the right way to proceed.

like image 836
Starlays Avatar asked Jun 04 '13 12:06

Starlays


2 Answers

Simple question you have to ask yourself:

Do all classes that extend this one do the same thing?

For this example, the answer is yes, they will all do

public function setWeelNum($weelNum) {
  $this->weelNum = $weelNum;
}

So don't copy/paste that code in each class, it's no point.

When should you declare an abstract method ?

When all the children of that class must implement this method but in different ways.

For example, in the class Animal, you will have a public abstract function move(); because all animals move, but you don't know how exactly.

like image 130
SteeveDroz Avatar answered Sep 18 '22 15:09

SteeveDroz


Generally, you should implement all methods in the last common ancestor. So if you want your children classes will behave the same way, implement them now. If they are to be implemented, but in many ways by different classes, leave them abstract.

Actually, an abstract class is done only for requiring that if somebody will inherit something from this common class, he will provide these methods (abstract class is something similar to interface).

If you implement all of them, there is no need to use an abstract class.

like image 43
Voitcus Avatar answered Sep 18 '22 15:09

Voitcus