Cainiao (1)-inheritance and combination in Java

Source: Internet
Author: User
Tags getcolor

Cainiao (1)-inheritance and combination in Java

The ability to read English is very important for programmers. I have been learning English over the past few years. Today, I have been searching for a brief blog article on the Internet. The level is average and the capability is limited. Please give more advice to the readers.


Translation:

This article will illustrate the concept of Java relay and combination. First, we will give an example of inheritance, and then demonstrate how to use combinations to improve the inheritance design. Finally, I will summarize how to make choices between them.

1. Inheritance

Suppose we have an Insect class. This class contains two methods: move () and attack ().

class Insect {private int size;private String color; public Insect(int size, String color) {this.size = size;this.color = color;} public int getSize() {return size;} public void setSize(int size) {this.size = size;} public String getColor() {return color;} public void setColor(String color) {this.color = color;} public void move() {System.out.println("Move");} public void attack() {move(); //assuming an insect needs to move before attackingSystem.out.println("Attack");}}


Now you want to define a Bee class, which is of the Insect type, but has different implementations of the attack () method and move () method. We can use inheritance for design, as shown below:

class Bee extends Insect {public Bee(int size, String color) {super(size, color);} public void move() {System.out.println("Fly");} public void attack() {move();super.attack();}}public class InheritanceVSComposition {public static void main(String[] args) {Insect i = new Bee(1, "red");i.attack();}}



The class hierarchy diagram is so simple:


Output:

<喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD48cHJlIGNsYXNzPQ = "brush: java;"> FlyFlyAttack

"Fly" is printed twice, indicating that move () is called twice. But it should be called once.

The problem lies in the super. attack () method. The attack () method of Insect calls the move () method. When the subclass calls super. attack (), it always calls the override move () method.


We can solve this problem using the following method:

Remove the attack () method of the subclass. This will make the subclass dependent on the implementation of the attack () method of the parent class. If the attack () method in the parent class changes (this is beyond your control), for example, attack () of the parent class () methods are implemented in other ways, and subclass needs to be changed. This is not a good design. Override attack () as follows:
public void attack() {move();System.out.println("Attack");}

This ensures the correct results, because the child class no longer depends on the parent class. However, the Code becomes a replica of the parent class. (Imagine that the attack () method is much more complex than printing a string.) This violates the software engineering Reuse Principle.

This inheritance is poorly designed because the subclass depends on the specific implementation of the parent class. If the parent class changes, the subclass will be damaged.

2. Combination

In contrast to inheritance, a combination can be used in this case. Let's take a look at the combined solution.

The attack method is abstracted as an interface.

interface Attack {public void move();public void attack();}

The Attack interface can be implemented in different ways.

class AttackImpl implements Attack {private String move;private String attack; public AttackImpl(String move, String attack) {this.move = move;this.attack = attack;} @Overridepublic void move() {System.out.println(move);} @Overridepublic void attack() {move();System.out.println(attack);}}

After the attack method is extracted, Insect is no longer associated with attack.

class Insect {private int size;private String color; public Insect(int size, String color) {this.size = size;this.color = color;} public int getSize() {return size;} public void setSize(int size) {this.size = size;} public String getColor() {return color;} public void setColor(String color) {this.color = color;}}

Bee is an Insect type that can be attacked.

// This wrapper class wrap an Attack objectclass Bee extends Insect implements Attack {private Attack attack; public Bee(int size, String color, Attack attack) {super(size, color);this.attack = attack;} public void move() {attack.move();} public void attack() {attack.attack();}}



Class diagram:




public class InheritanceVSComposition2 {public static void main(String[] args) {Bee a = new Bee(1, "black", new AttackImpl("fly", "move"));a.attack(); // if you need another implementation of move()// there is no need to change Insect, we can quickly use new method to attack Bee b = new Bee(1, "black", new AttackImpl("fly", "sting"));b.attack();}}

flymoveflysting

3. When to use inheritance and combination?

The following two items tell us how to choose between inheritance and combination:

If there is a "yes" relationship and a class needs to expose all interfaces to another class, inheritance is a better choice. If there is a "yes" relationship, the combination is preferred.

In short, inheritance and combination have their own purposes, and it is necessary to understand their advantages and disadvantages.


Finally, let's talk about how you feel. The younger brother has learned English since junior high school, and the score has never been better. The best score is just passing. I remember the English score of lz during the college entrance examination.55Score (enough to record the scores in History). How poor is my English? You can imagine it. Later, thanks to the teacher's instruction, I never gave up learning English. Now I still study English every day (although I have not mastered its essence, I have always learned better than I did not ). In the past, when I met a foreigner, I couldn't open my mouth, but I didn't know what to say. Now it's much better. I used to play football with a foreigner. I don't know what to say. It's also fun. In the past, I saw an English article and turned it off directly. Now I can calm down and see it.


In short, the mentality of learning English is very important, as long as you are not afraid of it, it is nothing to fear. Chairman Mao once said: "All the reactionaries are the Papertiger (All anti-moving schools are paper tigers )". There is nothing to worry about in English. When you meet a foreigner, you will get bored with him. The best thing you can do is to break your hands together-no one knows what to say. Are there any worse results? We won't lose in any way. What are you afraid? I can't read English articles or books, so I don't have to worry about it. It's a big deal to get a dictionary. I have a lot in hand and I'm afraid I can't help you with your little English. Don't hesitate. Come on, boy!


Original article: Inheritance vs. Composition in Java



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.