Rookie Translator (a)--java in succession and combination

Source: Internet
Author: User
Tags getcolor

Reading English program Ape's ability, which is very important. The past few years have been learning English, a whim today, on the internet to find what Bowen brief translation.

General level, limited capacity, crossing also ask you a lot of advice.


President

This article will illustrate the concepts of inheritance and composition in Java. First, give an example of inheritance. Then show how to use the combination to improve the inherited design. Finally, summarize how to make a choice between them.

1. Inheritance

Suppose we have a insect class. This class consists of two methods: one is move (). One is 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 col or;} public void SetColor (String color) {This.color = color,} public void Move () {System.out.println ("move"), public void Atta CK () {move ();//assuming an insect needs to move before AttackingSystem.out.println ("Attack");}}


Now you want to define a bee class, which is of type insect, but has a different implementation of the attack () method and the Move () method.

We are able to design with inheritance, as seen in the following:

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:

Flyflyattack


"Fly" was printed two times, indicating that move () was called two times. But it should have been called once before.

The problem is on the Super.attack () method. The insect Attack () method calls the Move () method. When a subclass calls Super.attack (), the overridden Move () method is always called.



We are able to solve the problem in the following ways:

    1. Remove the attack () method of the subclass.

      This will make the subclass dependent on the implementation of the parent class attack () method. Suppose the attack () method in the parent class changes (which you cannot control), such as: The Attack () method of the parent class is implemented in other ways, and the subclass needs to change, which is not a good design.

    2. Override the attack () method, such as the following:
      public void Attack () {move (); System.out.println ("Attack");}

      This guarantees the correct result, because the subclass is no longer dependent on the parent class. However. The code becomes a replica of the parent class.

      (Imagine that the attack () method is far more complex than printing a string), which violates the principle of software project reuse.

This inheritance is poorly designed because subclasses rely on a detailed implementation of the parent class, assuming the parent class changes. Subclasses will be destroyed.

2. Combination

In contrast to inheritance, a combination can be used in a situation like this.

Let's take a look at the solution to the use of composition first.

The attack method is abstracted as an interface.


Interface Attack {public void Move ();p ublic void Attack ();

The attack interface can be implemented in many different ways.

Class Attackimpl implements Attack {private string move;private string Attack; public Attackimpl (String move, String Attac K) {this.move = Move;this.attack = attack;} @Overridepublic void Move () {System.out.println (move);} @Overridepublic void A Ttack () {move (); System.out.println (attack);}}

By extracting the attack method, the 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 col or;} public void SetColor (String color) {this.color = color;}}

Bee is a insect type that is capable of attacking.

This wrapper class wrap a Attack objectclass Bee extends insect implements Attack {private Attack Attack; public Bee (i NT size, String color, Attack Attack) {super (size, color); this.attack = Attack;} public void Move () {Attack.move ();} publi c void Attack () {attack.attack ();}}



Class Diagram:

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvbgl1c2h1awppbmdlcg==/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma== /dissolve/70/gravity/center "/>



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 Atta CK Bee B = new Bee (1, "Black", New Attackimpl ("Fly", "sting")); B.attack ();}}

Flymoveflysting

3. When to use inheritance, when to use the combination?

Here are two things to tell us how to make a choice between inheritance and composition:

    1. Suppose there is a "yes" relationship, and a class exposes all interfaces to a class. Then inheritance is a better choice.
    2. Suppose there is a "have" relationship, then the preferred combination.

Anyway. Inheritance and combination have their uses, and understanding their pros and cons is very necessary.


Finally, say a little bit about your feelings. My little brother has started to learn English since junior high school. There's no better grades. The best grades have just passed. Remember when the college entrance examination of the LZ's English scores (enough to load the history of the Register), my English level how bad, we can imagine it.

Later thanks to the teacher's inculcation, has not given up English study. Today is still learning every day (though not mastering its essence.) But learning is better than not learning. I have never opened my mouth when I met a foreigner. Don't know what to say. It's much better now. Before often with foreigners to play football, nothing blind vernacular a few words, feel also quite fun.

Once saw the English article, the direct turn off, now also can calm down the heart to look down.


In short, learning English mentality is very important, just want you not afraid of it, it has nothing to fear.

Chairman Mao once said: All the reactionaries is the Papertiger ( all reactionaries are paper Tigers ).

English is nothing to be afraid of. When you meet a foreigner, you have to talk to him, the most incompetent you two tie--who can not understand who said what.

Any more bad results? No matter what, we will not lose. Then what are you afraid of? Read English articles, books can not understand. That is not to be afraid of, the big Deal a dictionary Bai. I have a lot of way in hand, but also afraid to cure you a little English. Don't hesitate, come on, Junior!


Original link: inheritance vs. composition in Java



Rookie Translator (a)--java in succession and combination

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.