0

Well since the very beginning I've though abstractions are pointless.. I just do not get whether one should use them or not - specially when working as freelancer without the help of anyone else.

Here's a little class I've made to demonstrate it. What I did in these classes could easily be done in regular class. There was no need for an abstract class. Can someone tell me where an abstract class would be useful in a small example please. I want to know when and why to use abstraction, I'm not asking

    abstract class Computer{
    abstract function turn_on();
    abstract function turn_of();
    abstract function activate_fan();
}

class Toshiba extends Computer{
    function turn_on(){
        echo __class__ ." is now on. Green light showing </br>";
        $this->activate_fan();
    }

    function turn_of(){
        echo __class__ ." is now of. No light showing </br>";
    }

    public function activate_fan(){
        echo __class__ . " Fan is now running, speed 300rps </br>";
    }
}


class Asus extends Computer{
    function turn_on(){
        echo __class__ ." is now on. Blue light showing </br>";
        $this->activate_fan();
    }

    function turn_of(){
        echo __class__ ." is now of. No light showing </br>";
    }

    public function activate_fan(){
        echo __class__ . " fan is now running, speed 80rps </br>";
    }
}

$Toshiba = new Toshiba;
$Asus = new Asus;

$Toshiba->turn_on();
$Asus->turn_on();
sami7913
  • 87
  • 7
  • 1
    Are you confusing abstract with interface? Your `Computer` class is effectively just defining empty methods, so shouldn't really be an abstract at all – Mark Baker Mar 13 '15 at 12:34
  • However, you could easily move all the turn_of() logic from eacho of the concrete classes into the abstract because it's identical.... then you don't need to duplicate code between `Asus` and `Toshiba` – Mark Baker Mar 13 '15 at 12:41
  • possible duplicate of [Interface vs Base class](http://stackoverflow.com/questions/56867/interface-vs-base-class) – MuertoExcobito Mar 13 '15 at 12:42
  • @MarkBaker that could also be done in a base/parent class though.. couldnt it – sami7913 Mar 13 '15 at 12:45
  • Yes, the ony significant difference between a base/parent class and an abstract class is that you can't intantiate an abstract class.... so you couldn't instantiate an abstract generic `Computer` only specific models of computer like `Asus` and `Toshiba`..... note that this isn't a particularly good example anyway – Mark Baker Mar 13 '15 at 12:47
  • However, for type hinting purposes, `Computer` would be a valid type-hint for a method argument, and then you could equally pass instances of `Toshiba` or `Asus` to that method – Mark Baker Mar 13 '15 at 12:49

1 Answers1

0

How about this example:

function restartComputers($computers) {
  foreach ($computers as $c) {
    $c->turn_of();
    $c->turn_on();
  }
}
Sameer
  • 4,379
  • 1
  • 23
  • 23