For all the non-programmers out there, here is an
example of how/why multiple inheritance might be used:
Consider a
futon. It is both a
bed and a
couch. So you want to use it as you'd usually use a bed, but you also want it to serve as a couch. So you want to
inherit from both, so that, using
polymorphism, it can be used as either.
But there's a
problem. You
sleep on a bed, but you can also sleep on a couch. You
sit on a couch to watch
TV, but you can do the same on a bed. In a
language like
C++, these
overlaps create
problems, which the
programmer has to fix, usually by
overriding the
conflicting
methods. In a case like this, that means a lot of work! This is why so many people hate multiple inheritance in C++.
In
Java, multiple inheritance works differently. You can't inherit from more than one
parent class; however, you can
implement as many
interfaces as you like.
For example, here is one way you can implement
futon in Java. Create two interfaces,
bedInterface and
couchInterface. Create two classes,
bed and
couch, each of which implements its respective interface. Now decide which of these classes more closely represents how you want
futon to act. Let's say you choose
bed. Have
futon extend bed, and implement
couchInterface. Now you have to implement any methods in
couchInterface which aren't in
bed. You can also override methods in
bed if you want to.
Here's the important part: Wherever possible, reference all
beds and
couches as their interfaces, rather than the classes themselves. This way,
futon can be used wherever
couch can be used, not just
bed. Also, this helps with
code maintenance, because you won't be able to add methods to
couch without changing
couchInterface, and you won't be able to compile if you add to
couchInterface without updating
futon. So you won't accidently
screw up futon later on.
Well, I went a little further with this than I intended. I hope it's useful. If anyone has any
trouble with this example, feel free to /msg me with
questions/
suggestions/
death threats.