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 the same in these two classes. The example assumes die, has_food?, food_amount=, and hungry= exist. The duplication is hard to maintain, and it gets worse with more animals. Inheritance can remove it.

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 repeated eat.

Feedback about page:

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



Table Of Contents