Programming Tutorials

Converting C++ Multiple-Inheritance Hierarchies to Java

By: Daniel Malcolm in C++ Tutorials on 2007-09-15  

C++ allows one class to inherit two or more base classes at the same time. Java does not. To understand the difference, consider the two hierarchies depicted here: In both cases, subclass C inherits classes A and B. However, in the hierarchy on the left, C inherits both A and B at the same time. In the one on the right, B inherits A, and C inherits B. By not allowing the inheritance of multiple base classes by a single subclass, Java greatly simplifies the inheritance model. Multiple inheritance carries with it several special cases that must be handled. This adds overhead to both the compiler and the run-time system, while providing only marginal benefit for the programmer.

Since C++ supports multiple inheritance and Java does not, you may have to deal with this issue when porting C++ applications to Java. While every situation is different, two general pieces of advice can be offered. First, in many cases, multiple inheritance is employed in a C++ program when there is actually no need to do so. When this is the case, just convert the class structure to a single-inheritance hierarchy. For example, consider this C++ class hierarchy that defines a class called House:

class Foundation {
// ...
};
class Walls {
// ...
};
class Rooms {
// ...
};
class House : public Foundation, Walls, Rooms {
// ...
};

Notice that House multiply inherits Foundation, Walls, and Rooms. While there is nothing wrong with structuring a C++ hierarchy like this, it is not necessary. For example, here is the same set of classes structured for Java:

class Foundation {
// ...
}
class Walls extends Foundation {
// ...
}
class Rooms extends Walls {
// ...
}
class House extends Rooms {
// ...
}

Here, each class extends the preceding one, with House becoming the final extension. Sometimes a multiple inheritance hierarchy is more readily converted by including objects of the multiply inherited classes in the final object. For example, here is another way that House could be constructed in Java:

class Foundation {
// ...
}
class Walls{
// ...
}
class Rooms {
// ...
}
/* Now, House includes Foundation, Walls, and Rooms
as object members.
*/
class House {
Foundation f;
Walls w;
Rooms r;
// ...
}

Here, Foundation, Walls, and Rooms are objects that are part of House rather than inherited by House.

One other point: sometimes a C++ program will contain a multiple-inheritance hierarchy simply because of poor initial design. A good time to correct this type of design flaw is when you port to Java.






Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in C++ )

Latest Articles (in C++)