Amazon Interview Question
Software Engineer / DevelopersThe question seems to be correct and make sense, not sure of java language - but java avoids multiple inheritance like C++ for simplicity reasons.
And multiple inheritance in Java can be achieved by using multiple inheritance of interfaces. Things may have changed since I touched java - 10 years back.
Multiple inheritance is not possible in java as it lead to ambiguity. For instance you have a class Drive, and it has 2 child classes CD_Drive and DVD_Drive. The drive class has a method burn (), which is inherited by the child classes CD_Drive and DVD_Drive. Now, lets say we have another child class, Combo_Drive which is inherited from both Cd_Drive and DVD_Drive ( This is multiple inheritance), Now the problem is which burn() version should the burn() should Combo_Drive Inherit, CD_Drive one or the DVD_Drive one. SO, to avoid this ambiguity java does not allow multiple inheritance.
But at times we need dual behavior. Like we want the combo drive to have the behavior of both cd_drive and dvd_drive. So, we can actually inherited from one of the classes, let say cd_drive and form a single level inheritance, which is valid in java and at the same time create and interface for that represent the other class which is the dvd_drive. Finally we can say class Combo_Drive extends cd_Drive and Class Combo_Drive implements dvd_Drive. Doing this we have incorporated the behavior of both cd_drive and dvd_drive in combo drive.
I tried to explain the solution to the best of my knowledge. I hope it helps!
In order to provide the functionalities of multiple inheritance in java , we have interfaces , and you can implement more than one interfaces , read about the same . Complete Reference is a good place to look for it.
ofcourse, you do have multiple inheritance for interfaces, but interfaces are only useful when they are implemented by classes. So, the main question here is how would you simulate multiple inheritance in java since you do not have multiple inheritance between classes. Then we can say using interfaces.
You don't need to simulate multiple inheritance in C++; it is already a feature. Could the question be simulating it in another language where it is not allowed?
- barcod April 16, 2011