Inheritance is used for Code resuse To support polymorphism Disadvantages of inheritance Difficult to change the interaface of the subclass Superclass is always instantiated Can get complex and unmanageable Composition is used for code reuse Disadvantages of composition We cannot use polymorphism We cannot extend the system by adding subclasses May have a slight performance overhead Usage Inheritance: IS- A Composition: HAS - A Example 1 : public class Car { private Engine engine; public void start () {} public void stop () {} } public class SUV extends Car { public void start () {} //overrides the start method from Car public void fourByFourMode () {} } Example 2 : public void someMethod () { Car c = new SUV () ; c.start () ; } Example 3 : public class Car { private Engine engine; public void start () { engine.start () ; //maybe do something more } public void stop () {} }
Write Awesome User Manuals and Tutorials for Software Products