Inheritance and composition are two of the most common ways to create new types in Java, both of which improve code reuse.
Inheritance is primarily intended to allow subclasses to inherit the basic nature of the parent class, which is often used to want to use the functionality of an existing class in a new class, rather than its interface. The difference between the two is the "is a" and "has a" relationship
Inherited:
classShape { Public voidDraw () {System.out.println ("Draw a Shape"); } Public voidErase () {System.out.println ("Erase"); }}classSquareextendsShape {@Override Public voidDraw () {System.out.println ("Draw a Square"); } Public Static voidMain (string[] args) {Square s=NewSquare (); S.draw (); S.erase (); }}
Combination:
classDraw { Public voidDraw () {System.out.println ("Draw"); }}classErase { Public voidErase () {System.out.println ("Erase"); }}classWork { Public voidWork () {NewDraw (). Draw (); NewErase (). Erase (); } Public Static voidMain (string[] args) {NewWork (). work (); }}
One, compared to the combination, inheritance has the following advantages:
1. In inheritance, subclasses automatically inherit the non-private members of the parent class and, when needed, can choose to use or override directly.
2. In inheritance, when you create a subclass object, you do not need to create the parent class object, because the system is automatically completed, and in the composition, when you create an object of a composite class, you typically create objects of all the classes that it uses.
Two, the advantages of the combination:
1. In combination, the combination class is low-coupled to the calling class, while the inheriting neutron class is highly coupled to the parent class.
2, can be dynamic combination.
Summarize:
Although inheritance is a major feature of OOP, it is often not recommended because it tends to complicate the structure and make it more prone to errors. Therefore, unless we are sure that using inheritance will make the program most efficient, we do not consider using it.
So how do we tell if we should use inheritance? The idea of Java programming provides a simple way to judge, is to consider "really need to change?" ”。
Java Inheritance and composition