Refactoring existing classes to use Inheritance

suggest change

Let’s say we have two classes, Cat and Dog.

class Cat
  def eat
    die unless has_food?
    self.food_amount -= 1
    self.hungry = false
  end
  def sound
    puts "Meow"
  end
end

class Dog
  def eat
    die unless has_food?
    self.food_amount -= 1
    self.hungry = false
  end
  def sound
    puts "Woof"
  end
end

The eat method is exactly the same in these two classes. While this works, it is hard to maintain. The problem will get worse if there are more animals with the same eat method. Inheritance can solve this problem.

class Animal
  def eat
    die unless has_food?
    self.food_amount -= 1
    self.hungry = false
  end
  # No sound method
end

class Cat < Animal
  def sound
    puts "Meow"
  end
end

class Dog < Animal
  def sound
    puts "Woof"
  end
end

We have created a new class, Animal, and moved our eat method to that class. Then, we made Cat and Dog inherit from this new common superclass. This removes the need for repeating code

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents