The Artima Developer Community
Sponsored Link

Dynamic Productivity with Ruby
A Conversation with Yukihiro Matsumoto, Part II
by Bill Venners
November 17, 2003

<<  Page 2 of 3  >>

Advertisement

Single Inheritance and Mix-Ins

Bill Venners: In an article, you wrote, "Ruby supports single inheritance only, which I consider a feature." Why is single-inheritance desirable, and what are mix-ins?

Yukihiro Matsumoto: Single inheritance is good because the whole class inheritance structure forms a single tree with a single root, named Object, and that is very easy to understand. In languages with multiple inheritance, the classes form a network, which is harder to understand.

But even though single inheritance is good because of its simple tree structure, sometimes we want to share features or methods between classes outside the lines of single inheritance. In that case in Java, you have to define an interface to share method signatures, then usually implement using some kind of delegation from one object to another. In Ruby, we define something called a module, which is like a class, but with some restrictions: namely, you can't create an instance of a module, and a module can't inherit from a class. So in Ruby, if you define a module that has methods and plug that module into a class, then that class will have those methods, both signatures and implementations. If you then plug the same module into another class, there will be two classes that share the implementation. This gives much of the benefit of multiple inheritance, but without destroying the simple tree model of single inheritance.

This approach of plugging in modules is called Mix-ins. Mix-ins originally started in LISP culture as a usage of multiple inheritance. In fact, a mix-in is actually a strict way of using multiple inheritance. So in LISP, it's a style of using multiple inheritance. In Ruby, we force you to use mix-ins by supporting classes and modules.

<<  Page 2 of 3  >>


Sponsored Links



Google
  Web Artima.com   
Copyright © 1996-2014 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us