Prev - DUP - Next - TOC

Inheritance


Classification of objects takes the form of a hierarchy in most cases. For instance, `cats' are `the mammals', and `the mammals' are `animals'. Chunks of a classification are inherited properties from basic chunks. Again, `animals' breath therefore `cats' breath.

It is written in ruby as the follows:

 ruby> class Animal
 ruby|   def breath
 ruby|     print "inhales,and breaths out\n"
 ruby|   end
 ruby| end
 nil
 ruby> class Cat<Animal
 ruby|   def bark
 ruby|     print "mew\n"
 ruby|   end
 ruby| end
 nil

The Cat class isn't given any definitions on how to breath, but will be inherited it from the Animal class. Thus, in this case, the `bark' feature is just appended.

 ruby> tama = Cat.new
 #<Cat:0xbd80e8>
 ruby> tama.breath
 inhales,and breaths out
 nil
 ruby> tama.bark
 mew
 nil

Though, the properties of the basic class (called parent class or superclass) are not always inherited to its derivative classes (children class or subclass). For instance, `birds' fly while `penguins' don't. In other words, penguins have most other properties (`laying the eggs', etc.) of birds except flying. It will be redefined.

Let's express in ruby:

 ruby> class Bird
 ruby|   def lay_egg
 ruby|     # do something ..
 ruby|   end
 ruby|   def fly
 ruby|     #...
 ruby|   end
 ruby|   #...
 ruby| end
 nil
 ruby> class Penguin<Bird
 ruby|   def fly
 ruby|     fail "Penguins can't fly"
 ruby|   end
 ruby| end
 nil

The above case will be written as something like this. However, I feel that it is not suitable to write knowledgebase-some in ruby.

Using inheritance with defining the common properties in superclass, we need only to append or to redefine the differences. Someone call a programming style like it `differential programming'. It is one of the merits of OOP.


Prev - DUP - Next - TOC