I'm new to OOP and learning about polymorphism using interfaces. There is a popular polymorphous example which is calculating area depending on shape.
The code:
<?php
interface Shape {
public function calcArea();
}
class Circle implements Shape {
private $radius;
public function __construct($radius) {
$this -> radius = $radius;
}
public function calcArea() {
return $this -> radius * $this -> radius * pi();
}
}
class Rectangle implements Shape {
private $width;
private $height;
public function __construct($width, $height) {
$this -> width = $width;
$this -> height = $height;
}
public function calcArea() {
return $this -> width * $this -> height;
}
}
$circ = new Circle(3);
$rect = new Rectangle(3,4);
echo $circ -> calcArea();
echo '<br />';
echo $rect -> calcArea();
?>
This is the same code without using interface at all:
<?php
class Circle {
private $radius;
public function __construct($radius) {
$this -> radius = $radius;
}
public function calcArea() {
return $this -> radius * $this -> radius * pi();
}
}
class Rectangle {
private $width;
private $height;
public function __construct($width, $height) {
$this -> width = $width;
$this -> height = $height;
}
public function calcArea() {
return $this -> width * $this -> height;
}
}
$circ = new Circle(3);
$rect = new Rectangle(3,4);
echo $circ -> calcArea();
echo '<br />';
echo $rect -> calcArea();
?>
Both work as expected but the interface has actually no use! Until now OOP seems just to add more layers of unnecessary complexity. Like instead of switch or if conditions, we use classes and a common interface. I find it actually more easy on the eye to just use the IF or switch conditions (as long as you don't keep repeating the same code) after each other instead of each one in a separate class.
The only benefit to OOP in general seems to be when designing an API. So the end user of the API can actually access the method needed directly without having to call a lot of unneeded code.
From developers side though, any modification you apply to a certain class may actually need to be done to other part of the code as well. Moreover, a developer anyway will have to take a look at other part of the code to be able understand how it works. Further more, inline PHP in HTML will be there so any modification of a certain method may need changes in the instances of the objects declared.
Am I missing something?