Multiple Inheritance

   

Java™ 2 Primer Plus
By Steven Haines, Steve Potts

Table of Contents
Chapter 8.  Interfaces


Assuming the behavior of multiple different objects is accomplished in many programming languages through multiple inheritance, or inheriting the functionality of more than one super class. There is a danger in multiple inheritance known as diamond inheritance, see Figure 8.1.

Figure 8.1. Diamond inheritance diagram.

graphics/08fig01.gif

In Figure 8.1, we have created a new PorschePinto hybrid car (scary huh?). You can see that the PorschePinto extends both Porsche and Pinto, which both extend Car. Numerous questions arise as to which implementation of a method is executed when it is called on the PorschePinto class. Consider the accelerate method: If the PorschePinto does not implement the accelerate method itself, does it accelerate like a Pinto or a Porsche? Furthermore, if you think about the creation process of classes in an inheritance hierarchy, all super classes must be created prior to their subclasses. In this scenario, there will be two instances of the Car class in memory for the PorschePinto. Now, if you start the PorschePinto by calling its start method, which instance of the two Car parents actually has its running variable set to true?

Because of all these questions and problems, Java has opted not to include support for multiple inheritance. Java supports single inheritance (one super class), and then works around the problem by allowing you to implement as many interfaces as you need. Because interfaces cannot provide any implementation, there is no ambiguity in which implementation of a method to execute. In some situations you might have to write more code because of this restriction, but it does solve a lot of problems.


       
    Top
     



    Java 2 Primer Plus
    Java 2 Primer Plus
    ISBN: 0672324156
    EAN: 2147483647
    Year: 2001
    Pages: 332

    Similar book on Amazon

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net