CSC/ECE 517 Fall 2012/ch1 1w23 as: Difference between revisions

From Expertiza_Wiki
Jump to navigation Jump to search
 
(122 intermediate revisions by 2 users not shown)
Line 2: Line 2:


==Introduction==
==Introduction==
 
The purpose of this article is to give a brief introduction about multiple inheritance, consider some of its issues and discuss techniques employed by different programming languages to handle such issues. In this relation, the article also compares solutions provided by different programming languages, especially against Ruby mixins, by listing their advantages and disadvantages.


==Multiple Inheritance==
==Multiple Inheritance==
Multiple Inheritance is a technique of establishing hierarchical relationships within a set of classes, such that a single class can inherit  behaviors from multiple parent classes. Although it might seem useful, to include methods from multiple classes, the major issue with multiple inheritance is the ambiguity in referencing the parent class methods,  when more than one parent classes share a method with the same name.This ambiguity is predominant in cases where the inheritance hierarchy is more than one level deep, where the class in the lowermost level inherits from two classes, that have overridden the same method from their parent in different ways.
Multiple Inheritance is a technique of establishing hierarchical relationships within a set of classes, such that a single class can inherit  behaviors from multiple parent classes. Although it might seem useful to include methods from multiple classes, the major issue with multiple inheritance is the ambiguity in referencing the parent class methods,  when more than one parent classes share a method with the same name.This ambiguity is predominant in cases where the inheritance hierarchy is more than one level deep, where the class in the lowermost level inherits from two classes, that have overridden the same method from their parent in different ways.<ref>http://en.wikipedia.org/wiki/Multiple_inheritance#The_diamond_problem</ref>


==A Real World Example==
==A Real World Example==
Let us consider an example of representing players of Cricket using classes and objects. The players of Cricket are instances of class Cricketer. Classes Bowler and Batsman inherit Cricketer’s state and behavior. All rounders inherit states and behaviors of Batsman, Bowler and subsequently from the Cricketer through Batsman and Bowler classes. Let us explore the issues of multiple inheritance in reference to this context.
A known example of multiple inheritance to represent winged animals and mammals, using classes and objects is cited here <ref> http://stackoverflow.com/questions/9359948/multiple-inheritance-whats-a-good-example</ref>. A Winged animal and a mammal inherit primitive attributes of an animal. While a winged animal can fly; a mammal can breathe and reproduce; they both eat, move and share features generic to animals. A bat being a winged mammal possesses features common to both winged animal and mammal. It follows that class Bat inherits from classes WingedAnimal and Mammal and in turn classes WingedAnimal and Mammal inherit from class Animal.   In reference to this context, let us write our own implementation and explore the issues of multiple inheritance.


[[File:Class_Diagram.png|thumb|right|x400px|alt=Class Diagram for the example.]]
[[File:Class_Diagram_-_Example.jpeg|thumb|right|x300px|alt=Class Diagram for the example.]]


==Issues of Multiple Inheritance==
==Issues of Multiple Inheritance==
1. Due to inheritance, the parent class’s objects get duplicated to child class. As a result, Allrounder Class duplicates Cricketer objects through each of Batsman and Bowler classes. When Allrounder accesses any of the Cricketer’s attributes, the compiler would be ambiguous about determining the correct path to use since two paths are available from Allrounder to Cricketer. This problem of multiple inheritance is called diamond problem. Compiler takes arbitrary decisions during such situations.  
<ul>
<li> Due to inheritance, the parent class’s objects get duplicated to child class. As a result, Class Bat duplicates Animal objects through each of WingedAnimal and Mammal classes. When Bat accesses any of the Animal's attributes, the compiler would be ambiguous about determining the correct path to use since two paths are available from Animal to Bat. This problem of multiple inheritance is called diamond problem <ref>http://www.artima.com/weblogs/viewpost.jsp?thread=246488</ref>. Compiler takes arbitrary decisions during such situations. </li>


2.Objects of parent classes can be separately managed by using virtual tables as in C++. By explicitly specifying the virtual table pointer, the Allrounder class can access Batsman and Bowler classes unambiguously. However virtual tables occupy significant portion of memory thereby limiting their extensive usage.
<li> Objects of parent classes can be separately managed by using [http://en.wikipedia.org/wiki/Virtual_method_table virtual tables]as in C++. By explicitly specifying the virtual table pointer, the Bat class can access WingedAnimal and Mammal classes unambiguously. However virtual tables occupy significant portion of memory thereby limiting their extensive usage. </li>


3. The order by which a child class inherits parent classes also matters. If Allrounder inherits Batsman prior to Bowler, then Batsman precedes Bowler and common methods are accessed in this order of precedence.  Hence if the Programmer is not aware of such precedences, debugging would be difficult.
<li> The order by which a child class inherits parent classes also matters. If Bat inherits WingedAnimal prior to Mammal, then WingedAnimal precedes Mammal and common methods are accessed in this order of precedence.  Hence if the Programmer is not aware of such precedence, debugging would be difficult. </li>
</ul>


==Solutions==
==Solutions==
Programming languages provide different solutions to handle the issues of multiple inheritance. Here we consider the techniques offered by C++, Java and Ruby.     
Programming languages provide different solutions to handle the issues of multiple inheritance. Here we consider the techniques offered by C++, Java, Ruby, Scala and Python.     
===Multiple Inheritance in C++===
===Multiple Inheritance in C++===
C++ supports multiple inheritance with the notion of virtual classes and functions. In the example, the Cricketer class defines virtual functions with Batsman and Bowler classes virtually inheriting the features of Cricketer. The Allrounder class can now unambiguously access Cricketer class using virtual table pointers of Batsman and Bowler. The example written using C++ virtual functions is shown below.
C++ supports multiple inheritance with the notion of virtual classes and virtual functions. In the example, the Animal class defines virtual function canEat() with WingedAnimal and Mammal classes virtually inheriting the features of Animal. The Bat class can now unambiguously access canEat() method of Animal class, using virtual table pointers of WingedAnimal and Mammal. The example written using C++ virtual functions is shown below.


class Cricketer
class Animal
{
{
  protected:
    char* country;
    char* player_type;
   public:
   public:
    virtual void statistics()
  void virtual canEat() {
    {
  }
        cout<<"Cricketer's statistics include number of matches, average, best performances etc."<<endl; }
};
    }  
};


class Batsman : virtual public Cricketer
class WingedAnimal :virtual public Animal
{
{
   public:
   public:
    void statistics()
  void canFly() {
    {
  }
      cout<<"Batsman's statistics include batting average, number of 100's & 50's, top score etc."<<endl;
  void canEat() {
    }
  }
        // other methods to operate on Cricketer & Batsman specific attributes
};
};


class Bowler : virtual public Cricketer
class Mammal :virtual public Animal
{
{
   public:
   public:
    void statistics()
  void canGiveBirth() {
    {
  }
      cout<<"Bowler's statistics include number of wickets, bowling average, economy etc."<<endl;
  void canEat() {
    }
  }
      // other methods to operate on Cricketer & Bowler specific attributes
};
};


class Allrounder: public Batsman, public Bowler
class Bat :public WingedAnimal, public Mammal
{
{
   public:
   public:
    void statistics()
  void canFly() {
    {
  }
      cout<<"Allrounder's statistics include batting average, bowling average etc."<<endl;
  void canGiveBirth() {
    }
  }
    // other methods to operate on Cricketer, Batsman & Bowler specific attributes
};
};


int main()
int main()
{
{
   int i = 0;
   int i = 0;
   Cricketer *instances[3];
   Animal *instances[3];
   Batsman bat;
   WingedAnimal w;
   Bowler bowl;
   Mammal m;
   Allrounder all;
   Bat b;
   instances[0] = &bat;
   instances[0] = &w;
   instances[1] = &bowl;
   instances[1] = &m;
   instances[2] = &all;
   instances[2] = &b;
   while(i<3)  
   while(i<3)
     instances[i++]->statistics();    
     instances[i++]->canEat();
   return 0;
   return 0;
}
}


===Multiple Inheritance in Java===
===Multiple Inheritance in Java===
Java doesn’t support multiple inheritance but provides a feature called interfaces to resemble inheritance from multiple classes. Interface is an abstract class which provides a generic template by just declaring variables and methods without definition. Concrete classes that inherits interfaces are supposed to implement its methods. The example written using Java interfaces is shown below.
Java doesn’t support multiple inheritance but provides a feature called interfaces to simulate inheritance from multiple classes. Interface is an abstract class which provides a generic template by just declaring variables and methods without implementing them. [http://www.brpreiss.com/books/opus4/html/page611.html Concrete classes] that inherit interfaces are supposed to implement its methods. The example written using Java interfaces is shown below.


interface Cricketer
interface Animal
{
{
  void statistics();   
  void canEat();   
}
}


interface Batsman extends Cricketer
interface WingedAnimal extends Animal
{
{
  void statistics();
  void canEat();
  // other methods to operate on Cricketer & Batsman specific attributes
  void canFly(); 
}
}
class ImplementWingedAnimal implements WingedAnimal 
{
    public void canEat() {   
    }
    public void canFly() {   
    }
}


interface Bowler extends Cricketer
interface Mammal extends Animal
{
{
  void statistics();
  void canEat();
  // other methods to operate on Cricketer & Bowler specific attributes
  void canGiveBirth();
}
}
class ImplementMammal implements Mammal
{
    public void canEat() {   
    }
    public void canGiveBirth() {   
    }   
}


interface Allrounder extends Batsman, Bowler
interface Bat extends WingedAnimal, Mammal
{
{
   // other methods to operate on Cricketer, Batsman & Bowler specific attributes
    void canEat();    
}
}


class ImplementBatsman implements Batsman  
class ImplementBat implements Bat
{
{  
     public void statistics()
    ImplementWingedAnimal w = new ImplementWingedAnimal();
    {
    ImplementMammal m = new ImplementMammal();   
       System.out.println("Batsman's statistics include batting average, number of 100's & 50's etc.");
     public void canEat() {          
     }  
       m.canEat(); 
     // other methods to operate on Cricketer & Batsman specific attributes
      w.canEat();    
}
     }
 
     public void canFly() {
class ImplementBowler implements Bowler
    }
{
     public void canGiveBirth() {
     public void statistics()
    {
      System.out.println("Bowler's statistics include number of wickets, bowling average, economy etc.");
     }     
     }     
    // other methods to operate on Cricketer & Bowler specific attributes
}
}


class ImplementAllrounder implements Allrounder
public class MultipleInheritance
{
{
    ImplementBowler bowl = new ImplementBowler();
  public static void main(String args[])
    ImplementBatsman bat = new ImplementBatsman();  
  {
    ImplementBat b = new ImplementBat ();
    b.canEat();      
  }
}


    public void statistics()
===Multiple Inheritance in Ruby===
    {
Ruby doesn't support multiple inheritance but provides a similar feature using modules and mixins.
      bowl.statistics();
====Modules====
      bat.statistics(); 
A Module is an encapsulation of methods and variables, although similar in function to a Class, differs from a class in the sense that it cannot be instantiated. Modules are  more dynamic and allow us to organize the code in a more granular way.Each module can add something to the existing class. A module can be thought of an encapsulation of a  subset of the full capabilities of an object.
    }   
An example found in the book ,The Well-Grounded Rubyist <ref>http://www.manning.com/black2/SampleChapter4.pdf [Pg.92] </ref>, is the stack-like module. The module encapsulates the characteristics of being like a stack,implements the operations that can be performed by a stack but is not the actual Stack class. This allows us to use this module to mix-in  stack-like behaviour into other classes that require them.
    // other methods to operate on Cricketer, Batsman & Bowler specific attributes
}
public class MultipleInheritance
{
  public static void main(String args[])
  {
    ImplementAllrounder all = new ImplementAllrounder();
    all.statistics();     
  }
}


===Mixins in Ruby===
====Mixins====
Ruby doesn’t support multiple inheritance but provides a more similar feature using mixins. The example written using ruby mixins is shown below.
A Mixin is a concept that allows inclusion of special characteristics into existing classes, so that common features that need to be reused in several classes can be selectively included, thus avoiding implementation of unnecessary functions like in the case of interfaces.
Mixins allow us to dynamically bind special features defined in modules, into core classes without really making any changes to the objects. This improves flexibility when we want to add plugins and extensions to the existing framework.<ref>http://www.innovationontherun.com/why-rubys-mixins-gives-rails-an-advantage-over-java-frameworks/</ref>.The source code for the same example implemented using ruby mixins is shown below.


module Cricketer
module Animal
  def statistics
  def canEat      
     puts "Cricketer's statistics include number of matches, average etc."
  end   
  end   
end
end


module Batsman
module WingedAnimal
  include Cricketer
  include Animal   
  def statistics
  def canEat
    puts "Batsman's statistics include batting average, number of 100's & 50's etc."
  end     
  end  
  def canFly
end
  end    
end


module Bowler
module Mammal
  include Cricketer
  include Animal
  def statistics
  def canEat
    puts "Bowler's statistics include number of wickets, bowling average, economy etc."
  end
  end   
  def canGiveBirth
end
  end   
end


class AllRounder
class Bat
  include Batsman
  include WingedAnimal
  include Bowler
  include Mammal
  include Cricketer
  include Animal 
  # Other implementation
end
end
 
all = AllRounder.new()
Bat.new().canEat()
all.statistics()


===Multiple inheritance in other languages===
===Multiple inheritance in other languages===
Scala offers traits that are similar to Java interfaces to support multiple inheritance. Traits define a template with methods and variables which any class can make use of. The difference between interfaces and traits is that traits can implement methods. A Scala class can inherit from any number of traits together with a class in way to support multiple inheritance. Traits can be mixed in to a class even without inheriting it but just by including it at the time of instantiation The language enforces method names to be different across inherited  traits to avoid the issues of multiple inheritance. Python supports a limited version of multiple inheritance by extending multiple classes in depth-first left-right order. If a python class D inherits classes A, B, C and if an instance variable or method is not available in the current class, it checks in A and its base classes, then moves to B and its base classes and eventually to C thus moving from left to right. In this way, python avoids the diamond problem by linearizing the search order by which the derived class accesses attributes of its parent classes. In addition python also defines mixins to access reusable features within a class.
[http://www.scala-lang.org/ Scala] offers [http://www.scala-lang.org/node/126 traits] that are similar to Java interfaces to support multiple inheritance. Traits define a template with methods and variables which any class can make use of. The difference between interfaces and traits is that traits can implement methods. A Scala class can inherit from any number of traits together with a class in a way to support multiple inheritance. Traits can be mixed in to a class even without inheriting it but just by including it at the time of creating instances similar to extend feature in ruby. <ref>http://joelabrahamsson.com/entry/learning-scala-traits</ref>. Trait can also extend a class and methods to be overridden are usually prefixed by the keyword override. The language enforces method names to be different across inherited  traits to avoid the issues of multiple inheritance. [http://www.python.org/ Python] supports a limited version of multiple inheritance by extending multiple classes in depth-first left-right order <ref>http://docs.python.org/tutorial/classes.html</ref>. If a python class D inherits classes A, B, C and if an instance variable or method is not available in the current class, it checks in A and its base classes, then moves to B and its base classes and eventually to C thus moving from left to right. In this way, python avoids the diamond problem by making the search order linear, by which the derived class accesses attributes of its parent classes. In addition python also defines mixins to access reusable features within a class.


==Questions to ponder==
==Advantages of mixins==
===Do mixins solve all of these problems?===
<ul>
Undoubtedly mixins solve some of the problems of multiple inheritance. There is no ambiguity in resolving the request to a common method implemented by multiple modules. In that case, the lastly included module is responsible for handling accesses to common methods. Though the order of precedence of included modules matters, it looks clearer than C++.  However languages like Scala and Eiffel implement multiple inheritance far more safely  by explicitly forcing the user to have different method names across inherited classes.  
<li> Firstly, when a module gets mixed into different classes, each class acquires the same  reference  to the module and hence even dynamic changes to the module gets reflected in the behavior of the classes <ref>http://www.linuxtopia.org/online_books/programming_books/ruby_tutorial/Ruby_Modules_Mixins.html</ref>. In this way, the module’s code is not just copied to individual classes as in static languages instead its reference is provided. </li>
 
<li> Secondly, the mixed in state and behavior can be accessed by the instance of target class just like accessing its own features. </li>
 
<li> Thirdly, a class can include any number of modules in a way it can simulate multiple inheritance without having the related issues. </li>
</ul>
 
==Questions to Ponder==
===Do mixins solve all of the problems of multiple inheritance?===
Undoubtedly mixins solve some of the problems of multiple inheritance. There is no ambiguity in resolving the request to a common method implemented by multiple modules. In that case, the lastly included module is responsible for handling accesses to common methods. Though the order of precedence of included modules matters, it looks clearer than C++.  However languages like Scala and Eiffel implement multiple inheritance far more safely  by explicitly forcing the user to have different method names across inherited classes.


===Are mixins a clear advantage over interfaces?===
===Are mixins a clear advantage over interfaces?===
Mixins are more advantageous than interfaces because of their features. Interface is a concept to simulate multiple inheritance and is not as powerful as C++. As seen from programs, the derived class Allrounder uses the instances of Batsman and Bowler classes (has-a relationship) to access respective attributes. Interface is nice in the sense it provides a generic template that could be implemented differently by different classes.  However the target class has to necessarily implement every method of the interface. This would pose problems to a Class which is interested in implementing specific features of the interface. On the contrary, Mixins eliminates this inconvenience by mixing in the state and behavior of the modules in the target class and allows a it to use them as it needs. Hence the target class can just use module’s features selectively or completely instead of implementing by itself. The size of multiple inheritance code using mixins is smaller than interfaces and C++ variants.
Mixins are more advantageous than interfaces because of their features. Interfaces have some limitations. As seen from the example, the derived class Bat uses the instances of WingedAnimal and Mammal classes (has-a relationship) to access respective attributes. Interface is nice in the sense it provides a generic template that could be implemented differently by different classes.  However the target class has to necessarily implement every method of the interface. This would pose problems to a Class which is interested in implementing specific features of the interface. On the contrary, Mixins eliminate this inconvenience by mixing in the state and behavior of the modules in the target class and allows it to use them as it needs. Hence the target class can just use module’s features selectively or completely instead of implementing by itself. The size of multiple inheritance code using mixins is smaller than interfaces and C++ variants and this is obvious from the example.


===Do mixins have any disadvantages not shared by multiple inheritance or interfaces?===
===Do mixins have any disadvantages not shared by multiple inheritance or interfaces?===
Inspite of making the lives of programmers better with effective code reuse and avoiding unnecessary implementation of methods that cause clutter in the code, the concept of Mixins can easily be abused resulting in namespace pollution. This is caused when a class includes multiple modules each of which contains several hundred method implementations. Having hundreds of methods mixed into a single class, makes it difficult to identify the source modules of the methods, thereby causing confusion while implementing these methods, whereas in the case of multiple inheritance we can easily identify the class to which the method belongs.
Inspite of making the lives of programmers better with effective code reuse and avoiding unnecessary implementation of methods that cause clutter in the code, the concept of Mixins can easily be abused resulting in namespace pollution. This is caused when a class includes multiple modules each of which contains several hundred method implementations. Having hundreds of methods mixed into a single class, makes it difficult to identify the source modules of the methods, thereby causing confusion while implementing these methods, whereas in the case of multiple inheritance we can easily identify the class to which the method belongs.
Another disadvantage that follows from the namespace collision is the case where we have multiple methods with the same name in different modules.In such a case whenever a call to that method is made, the method which belongs to the module that was included last will be called. The problem with this is that, this takes place silently without any warning. This may result in accidental overriding of wrong methods.
Another disadvantage that follows from the namespace collision is the case where we have multiple methods with the same name in different modules.In such a case whenever a call to that method is made, the method which belongs to the module that was included last will be called. In the above example, the method call canEat() invokes Animal's canEat() method since Animal was the last included module. The problem with this is that, this takes place silently without any warning. This may result in accidentally inheriting wrong methods.
 
==References==
http://www.innovationontherun.com/why-rubys-mixins-gives-rails-an-advantage-over-java-frameworks/


http://www.pxleyes.com/blog/2010/02/pros-and-cons-of-3-popular-css-meta-frameworks/
==Conclusion==
In this article, we have discussed about multiple inheritance and means by which it is implemented in different languages. Though multiple inheritance is a useful feature,
many languages do not support them due to its associated issues. Given its advantages, mixin in ruby seems to be a viable option to achieve multiple inheritance. However mixins too have limitations which should be taken care of during implementation.


http://www.artima.com/weblogs/viewpost.jsp?thread=246488
==References==
 
<references/>
http://www.linuxtopia.org/online_books/programming_books/ruby_tutorial/Ruby_Modules_Mixins.html
==See Also==
1. Dominic Duggan and Ching Ching Techaubol- OOPSLA '01 Proceedings of the 16th ACM SIGPLAN conference on Object-oriented programming, systems, languages, and applications, :[http://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=10&ved=0CF8QFjAJ&url=http%3A%2F%2Fciteseerx.ist.psu.edu%2Fviewdoc%2Fdownload%3Fdoi%3D10.1.1.111.6648%26rep%3Drep1%26type%3Dpdf&ei=Pp9cULzCF4-E9QSc_YDwCw&usg=AFQjCNG8xhSWsH832wD2scfm8d5GdQCDzA          Modular Mixin-Based Inheritance for Application Frameworks ]


http://joelabrahamsson.com/entry/learning-scala-traits
2. Lucas Carlson and Leonard Richardson. 2006. [http://dl.acm.org.prox.lib.ncsu.edu/citation.cfm?id=1212915&coll=DL&dl=GUIDE&CFID=157189429&CFTOKEN=65094375 Ruby Cookbook] (Cookbooks (O'Reilly)). O'Reilly Media, Inc..


http://docs.python.org/tutorial/classes.html
3. Herbert Schildt. 2000. Java 2: [http://dl.acm.org.prox.lib.ncsu.edu/citation.cfm?id=557816&coll=DL&dl=GUIDE&CFID=157189429&CFTOKEN=65094375 The Complete Reference] (4th ed.). McGraw-Hill Professional.

Latest revision as of 17:50, 21 September 2012

1w23: Multiple Inheritance and Mixins

Introduction

The purpose of this article is to give a brief introduction about multiple inheritance, consider some of its issues and discuss techniques employed by different programming languages to handle such issues. In this relation, the article also compares solutions provided by different programming languages, especially against Ruby mixins, by listing their advantages and disadvantages.

Multiple Inheritance

Multiple Inheritance is a technique of establishing hierarchical relationships within a set of classes, such that a single class can inherit  behaviors from multiple parent classes. Although it might seem useful to include methods from multiple classes, the major issue with multiple inheritance is the ambiguity in referencing the parent class methods,  when more than one parent classes share a method with the same name.This ambiguity is predominant in cases where the inheritance hierarchy is more than one level deep, where the class in the lowermost level inherits from two classes, that have overridden the same method from their parent in different ways.<ref>http://en.wikipedia.org/wiki/Multiple_inheritance#The_diamond_problem</ref>

A Real World Example

A known example of multiple inheritance to represent winged animals and mammals, using classes and objects is cited here <ref> http://stackoverflow.com/questions/9359948/multiple-inheritance-whats-a-good-example</ref>. A Winged animal and a mammal inherit primitive attributes of an animal. While a winged animal can fly; a mammal can breathe and reproduce; they both eat, move and share features generic to animals. A bat being a winged mammal possesses features common to both winged animal and mammal. It follows that class Bat inherits from classes WingedAnimal and Mammal and in turn classes WingedAnimal and Mammal inherit from class Animal. In reference to this context, let us write our own implementation and explore the issues of multiple inheritance.

Class Diagram for the example.

Issues of Multiple Inheritance

  • Due to inheritance, the parent class’s objects get duplicated to child class. As a result, Class Bat duplicates Animal objects through each of WingedAnimal and Mammal classes. When Bat accesses any of the Animal's attributes, the compiler would be ambiguous about determining the correct path to use since two paths are available from Animal to Bat. This problem of multiple inheritance is called diamond problem <ref>http://www.artima.com/weblogs/viewpost.jsp?thread=246488</ref>. Compiler takes arbitrary decisions during such situations.
  • Objects of parent classes can be separately managed by using virtual tablesas in C++. By explicitly specifying the virtual table pointer, the Bat class can access WingedAnimal and Mammal classes unambiguously. However virtual tables occupy significant portion of memory thereby limiting their extensive usage.
  • The order by which a child class inherits parent classes also matters. If Bat inherits WingedAnimal prior to Mammal, then WingedAnimal precedes Mammal and common methods are accessed in this order of precedence. Hence if the Programmer is not aware of such precedence, debugging would be difficult.

Solutions

Programming languages provide different solutions to handle the issues of multiple inheritance. Here we consider the techniques offered by C++, Java, Ruby, Scala and Python.

Multiple Inheritance in C++

C++ supports multiple inheritance with the notion of virtual classes and virtual functions. In the example, the Animal class defines virtual function canEat() with WingedAnimal and Mammal classes virtually inheriting the features of Animal. The Bat class can now unambiguously access canEat() method of Animal class, using virtual table pointers of WingedAnimal and Mammal. The example written using C++ virtual functions is shown below.

class Animal
{
 public:
 void virtual canEat() {
 }
};
class WingedAnimal :virtual public Animal
{
 public:
 void canFly() {
 }
 void canEat() {
 }
};
class Mammal :virtual public Animal
{
 public:
 void canGiveBirth() {
 }
 void canEat() {
 }
};
class Bat :public WingedAnimal, public Mammal
{
 public:
 void canFly() {
 }
 void canGiveBirth() {
 }  
};
int main()
{
 int i = 0;
 Animal *instances[3];
 WingedAnimal w;
 Mammal m;
 Bat b;
 instances[0] = &w;
 instances[1] = &m;
 instances[2] = &b;
 while(i<3)
   instances[i++]->canEat();
 return 0;
}

Multiple Inheritance in Java

Java doesn’t support multiple inheritance but provides a feature called interfaces to simulate inheritance from multiple classes. Interface is an abstract class which provides a generic template by just declaring variables and methods without implementing them. Concrete classes that inherit interfaces are supposed to implement its methods. The example written using Java interfaces is shown below.

interface Animal
{
  void canEat();  
}
interface WingedAnimal extends Animal
{
  void canEat();  
  void canFly();  
}
class ImplementWingedAnimal implements WingedAnimal  
{
   public void canEat() {    
   }
   public void canFly() {    
   }
}
interface Mammal extends Animal
{
  void canEat();
  void canGiveBirth();
}
class ImplementMammal implements Mammal
{
   public void canEat() {    
   }
   public void canGiveBirth() {    
   }    
}
interface Bat extends WingedAnimal, Mammal
{
   void canEat();    
}
class ImplementBat implements Bat
{  
   ImplementWingedAnimal w = new ImplementWingedAnimal();
   ImplementMammal m = new ImplementMammal();     
   public void canEat() {            
     m.canEat();  
     w.canEat();      
   }
   public void canFly() {
   }
   public void canGiveBirth() {
   }    
}
public class MultipleInheritance
{
  public static void main(String args[])
  {
    ImplementBat b = new ImplementBat ();
    b.canEat();       
  } 
}

Multiple Inheritance in Ruby

Ruby doesn't support multiple inheritance but provides a similar feature using modules and mixins.

Modules

A Module is an encapsulation of methods and variables, although similar in function to a Class, differs from a class in the sense that it cannot be instantiated. Modules are more dynamic and allow us to organize the code in a more granular way.Each module can add something to the existing class. A module can be thought of an encapsulation of a subset of the full capabilities of an object. An example found in the book ,The Well-Grounded Rubyist <ref>http://www.manning.com/black2/SampleChapter4.pdf [Pg.92] </ref>, is the stack-like module. The module encapsulates the characteristics of being like a stack,implements the operations that can be performed by a stack but is not the actual Stack class. This allows us to use this module to mix-in stack-like behaviour into other classes that require them.

Mixins

A Mixin is a concept that allows inclusion of special characteristics into existing classes, so that common features that need to be reused in several classes can be selectively included, thus avoiding implementation of unnecessary functions like in the case of interfaces. Mixins allow us to dynamically bind special features defined in modules, into core classes without really making any changes to the objects. This improves flexibility when we want to add plugins and extensions to the existing framework.<ref>http://www.innovationontherun.com/why-rubys-mixins-gives-rails-an-advantage-over-java-frameworks/</ref>.The source code for the same example implemented using ruby mixins is shown below.

module Animal
  def canEat     
  end  
end
module WingedAnimal
  include Animal    
  def canEat
  end      
  def canFly
  end      
end
module Mammal
  include Animal
  def canEat
  end
  def canGiveBirth
  end  
end
class Bat
  include WingedAnimal
  include Mammal
  include Animal  
end
  
Bat.new().canEat()

Multiple inheritance in other languages

Scala offers traits that are similar to Java interfaces to support multiple inheritance. Traits define a template with methods and variables which any class can make use of. The difference between interfaces and traits is that traits can implement methods. A Scala class can inherit from any number of traits together with a class in a way to support multiple inheritance. Traits can be mixed in to a class even without inheriting it but just by including it at the time of creating instances similar to extend feature in ruby. <ref>http://joelabrahamsson.com/entry/learning-scala-traits</ref>. Trait can also extend a class and methods to be overridden are usually prefixed by the keyword override. The language enforces method names to be different across inherited traits to avoid the issues of multiple inheritance. Python supports a limited version of multiple inheritance by extending multiple classes in depth-first left-right order <ref>http://docs.python.org/tutorial/classes.html</ref>. If a python class D inherits classes A, B, C and if an instance variable or method is not available in the current class, it checks in A and its base classes, then moves to B and its base classes and eventually to C thus moving from left to right. In this way, python avoids the diamond problem by making the search order linear, by which the derived class accesses attributes of its parent classes. In addition python also defines mixins to access reusable features within a class.

Advantages of mixins

  • Firstly, when a module gets mixed into different classes, each class acquires the same reference to the module and hence even dynamic changes to the module gets reflected in the behavior of the classes <ref>http://www.linuxtopia.org/online_books/programming_books/ruby_tutorial/Ruby_Modules_Mixins.html</ref>. In this way, the module’s code is not just copied to individual classes as in static languages instead its reference is provided.
  • Secondly, the mixed in state and behavior can be accessed by the instance of target class just like accessing its own features.
  • Thirdly, a class can include any number of modules in a way it can simulate multiple inheritance without having the related issues.

Questions to Ponder

Do mixins solve all of the problems of multiple inheritance?

Undoubtedly mixins solve some of the problems of multiple inheritance. There is no ambiguity in resolving the request to a common method implemented by multiple modules. In that case, the lastly included module is responsible for handling accesses to common methods. Though the order of precedence of included modules matters, it looks clearer than C++. However languages like Scala and Eiffel implement multiple inheritance far more safely by explicitly forcing the user to have different method names across inherited classes.

Are mixins a clear advantage over interfaces?

Mixins are more advantageous than interfaces because of their features. Interfaces have some limitations. As seen from the example, the derived class Bat uses the instances of WingedAnimal and Mammal classes (has-a relationship) to access respective attributes. Interface is nice in the sense it provides a generic template that could be implemented differently by different classes. However the target class has to necessarily implement every method of the interface. This would pose problems to a Class which is interested in implementing specific features of the interface. On the contrary, Mixins eliminate this inconvenience by mixing in the state and behavior of the modules in the target class and allows it to use them as it needs. Hence the target class can just use module’s features selectively or completely instead of implementing by itself. The size of multiple inheritance code using mixins is smaller than interfaces and C++ variants and this is obvious from the example.

Do mixins have any disadvantages not shared by multiple inheritance or interfaces?

Inspite of making the lives of programmers better with effective code reuse and avoiding unnecessary implementation of methods that cause clutter in the code, the concept of Mixins can easily be abused resulting in namespace pollution. This is caused when a class includes multiple modules each of which contains several hundred method implementations. Having hundreds of methods mixed into a single class, makes it difficult to identify the source modules of the methods, thereby causing confusion while implementing these methods, whereas in the case of multiple inheritance we can easily identify the class to which the method belongs. Another disadvantage that follows from the namespace collision is the case where we have multiple methods with the same name in different modules.In such a case whenever a call to that method is made, the method which belongs to the module that was included last will be called. In the above example, the method call canEat() invokes Animal's canEat() method since Animal was the last included module. The problem with this is that, this takes place silently without any warning. This may result in accidentally inheriting wrong methods.

Conclusion

In this article, we have discussed about multiple inheritance and means by which it is implemented in different languages. Though multiple inheritance is a useful feature, many languages do not support them due to its associated issues. Given its advantages, mixin in ruby seems to be a viable option to achieve multiple inheritance. However mixins too have limitations which should be taken care of during implementation.

References

<references/>

See Also

1. Dominic Duggan and Ching Ching Techaubol- OOPSLA '01 Proceedings of the 16th ACM SIGPLAN conference on Object-oriented programming, systems, languages, and applications, :Modular Mixin-Based Inheritance for Application Frameworks

2. Lucas Carlson and Leonard Richardson. 2006. Ruby Cookbook (Cookbooks (O'Reilly)). O'Reilly Media, Inc..

3. Herbert Schildt. 2000. Java 2: The Complete Reference (4th ed.). McGraw-Hill Professional.