Code reuse is one of the good functions of Java. In general, Java provides two methods to achieve code reuse: Combination and inheritance.
Combination: Creates a new class based on the existing class object.
The combination is simple and intuitive, that is, to directly reference another class in a class, and then call some methods of the referenced class to complete some functions.
Instance:
class Engine{ public void start(){} public void stop(){} } class Door{ public void open(){} public void close(){} } class Window{ public void rollup(){} public void rolldown(){} } public class Car { private Engine engine=new Engine(); private Door door=new Door(); private Window window=new Window(); public static void main(String[] args) { Car car=new Car(); car.engine.start(); car.door.close(); car.window.rolldown(); } }
We can see that the combination is to explicitly place sub-objects in the new class, while the inheritance is implicitly done ......
Inheritance: use the existing class form without changing the existing class and add new code to it.
class Art{ Art(){ System.out.print("Art ~~~``"); } } class Drawing extends Art{ Drawing(){ System.out.print("Drawing ~~~``"); } } public class Cartoon extends Drawing{ public Cartoon(){ System.out.print("Cartoon ~~~``"); } public static void main(String[] args) { Cartoon c=new Cartoon(); } }
Conclusion: Selection of combination and inheritance
A combination is generally used to use the functions of an existing class in the new class instead of its interface. That is, the new class user only sees the interface defined for the new class.
Inheritance is used when the new class needs to be converted to the base class (polymorphism), which is also the clearest Judgment Method Used for combination and inheritance.
Although inheritance is strongly emphasized by object-oriented systems, it is generally used as a combination during design, and inheritance is used only when it is necessary,
Because the combination is more flexible .....
From http://lcy0202.iteye.com/blog/1473866