Rudy inheritance Concept

Source: Internet
Author: User

In daily life, we classify all objects at a certain level. we know that all cats are mammals, and all mammals are animals. small classes from larger
Class. If all the mammals want to breathe, then the CAT also needs to breathe.

In Ruby, we can express this concept as follows:

Ruby> class Mammal
| Def breathe
| Print "inhale and exhale \ n"
| End
| End
Nil
Ruby> class Cat <Mammal
| Def speak
| Print "Meow \ n"
| End
| End
Nil


Although we do not specify how a Cat breathe, Cat is defined as a subclass of Mammal (in OO terminology, a smaller class is called a subclass, A larger class is called the parent class), each cat inherits the behavior from the Mammal class. therefore, from the programmer's point of view, cats are naturally capable of breathing. When we add the speak method, our cats can breathe and speak.

Ruby> tama = Cat. new
# <Cat: 0xbd80e8>
Ruby> tama. breathe
Inhale and exhale
Nil
Ruby> tama. speak
Meow
Nil


Some attributes of the parent class cannot be inherited by a specific subclass. Although generally birds fly, penguins are not a subclass of birds.

Ruby> class Bird
| Def preen
| Print "I am cleaning my feathers ."
| End
| Def fly
| Print "I am flying ."
| End
| End
Nil
Ruby> class Penguin <Bird
| Def fly
| Fail "Sorry. I 'd rather swim ."
| End
| End
Nil


Aside from trying to define attributes for every new class, we only need to add or redefine the differences between the subclass and the parent class. this inherited usage is sometimes called feature programming (differential programming ). this is another advantage of object-oriented programming.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.