InterviewSolution
Saved Bookmarks
| 1. |
Although inheritance is a popular OOPs concept, it is less advantageous than composition. Explain. |
|
Answer» Inheritance lags BEHIND composition in the following scenarios:
Let’s take an example: package comparison;PUBLIC class Top {public int start() { return 0;}}class Bottom extends Top { public int stop() { return 0; }}In the above example, inheritance is FOLLOWED. Now, some modifications are done to the Top class like this: public class Top { public int start() { return 0; } public void stop() { }}If the new implementation of the Top class is followed, a compile-time error is bound to occur in the Bottom class. Incompatible return type is there for the Top.stop() function. Changes have to be made to either the Top or the Bottom class to ensure compatibility. However, the composition technique can be utilized to solve the given problem: class Bottom { Top par = new Top(); public int stop() { par.start(); par.stop(); return 0; }} |
|