Why would you extend a class rather than just adding a new method to the original class?

extend, methods, oop, php

Solution

If you want to add functionality to a class you add a method. However, there are situations that you want to add functionality, but cannot do that in a base class.

The best is show with a example. When adding a method `Radius` to a class makes only sense if the class is a `Circle`, a `Rect` has no radius. Adding a method `Radius` to the base class also makes no sense, because the `Rect` class then also gets a method `Radius`.

Example:

abstract class Shape
{
  abstract public function Draw();
}

class Rect extends Shape
{
  public function Draw()
  {
  }
}

class Circle extends Shape
{
  public function Draw()
  {
  }

  public function Radius()
  {
  }
}

Problem

I finally had my Ah-ha moment when it came to classes in OOP. I've been struggling to get my mind around the idea. Now that I'm starting to get it I was wondering what the purpose of extending a class is. Would it not be simpler to just add another method into the class or am I just missing the point?

Original source