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.