Evgenii Legotckoi
June 27, 2016, 12:38 p.m.

User Guide #13 - Ruby - Inheritance

Our classification of objects in everyday life is naturally hierarchical. We know that all cats are mammals , and all mammals are animals . Smaller classes inherit characteristics from the larger classes to which they belong. If all mammals breathe, then all cats breathe.

We can express this concept in ruby:

  1. ruby> class Mammal
  2. | def breathe
  3. | print "inhale and exhale\n"
  4. | end
  5. | end
  6. nil
  7. ruby> class Cat<Mammal
  8. | def speak
  9. | print "Meow\n"
  10. | end
  11. | end
  12. nil

Though we didn't specify how a Cat should breathe, every cat will inherit that behavior from the Mammal class since Cat was defined as a subclass of Mammal . (In OO terminology, the smaller class is a subclass and the larger class is a superclass .) Hence from a programmer's standpoint, cats get the ability to breathe for free; after we add a

  1. speak
method, our cats can both breathe and speak.


  1. ruby> tama = Cat.new
  2. #<Cat:0xbd80e8>
  3. ruby> tama.breathe
  4. inhale and exhale
  5. nil
  6. ruby> tama.speak
  7. Meow
  8. nil

There will be situations where certain properties of the superclass should not be inherited by a particular subclass. Though birds generally know how to fly, penguins are a flightless subclass of birds.

  1. ruby> class Bird
  2. | def preen
  3. | print "I am cleaning my feathers."
  4. | end
  5. | def fly
  6. | print "I am flying."
  7. | end
  8. | end
  9. nil
  10. ruby> class Penguin<Bird
  11. | def fly
  12. | fail "Sorry. I'd rather swim."
  13. | end
  14. | end
  15. nil

Rather than exhaustively define every characteristic of every new class, we need only to append or to redefine the differences between each subclass and its superclass. This use of inheritance is sometimes called differential programming . It is one of the benefits of object-oriented programming.

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • IscanderChe
    April 12, 2025, 5:12 p.m.
    Добрый день. Спасибо Вам за этот проект и отдельно за ответы на форуме, которые мне очень помогли в некоммерческих пет-проектах. Профессиональным программистом я так и не стал, но узнал мно…
  • AK
    April 1, 2025, 11:41 a.m.
    Добрый день. В данный момент работаю над проектом, где необходимо выводить звук из программы в определенное аудиоустройство (колонки, наушники, виртуальный кабель и т.д). Пишу на Qt5.12.12 поско…
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…