Cainiao translation (1)-inheritance and combination in Java

Source: Internet
Author: User
Tags getcolor

Cainiao translation (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:

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:

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:

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




Cainiao in cainiao helps a question about java inheritance

I wrote one, but I don't know if it meets your requirements.
Class Person {
String name;
String birth;
Person (String n, String B ){
Name = n;
Birth = B;
}
Public void getName (){
System. out. println ("name =" + name );
}
Public void getBirth (){
System. out. println ("birth =" + birth );
}
}
Class Student extends Person {
String major;
Student (String n, String B, String m ){
Super (n, B );
Major = m;
}
Public void getMajor (){
System. out. println ("major =" + major );
}
}
Class extends uctor extends Person {
Double salary;
Instructor (String n, String B, double s ){
Super (n, B );
Salary = s;
}
Public void getSalary (){
System. out. println ("salary =" + salary );
}
}

Public class Test {

/**
* @ Param args
*/
Public static void main (String [] args ){
// TODO Auto-generated method stub

Student s = new Student ("xiao li", "1990-05-18", "math ");
Extends uctor I = new extends uctor ("lao wang", "1980-11-24", 3425.78 );
System. out. println ("Student Information :");
S. getName ();
S. getBirth ();
S. getMajor ();
System. out. println ("Instructor Information :");
I. getName ();
I. getBirth ();
I. getSalary ();
}

}

Q: What is the difference between inheritance and interfaces in java? Take a closer look, cainiao.

Inheritance is an extended command. A class can only inherit one parent class, class A extended B, and class C are incorrect. After inheritance, subclass can use the parent class method.
The interface is the implements command. A class can have many interfaces. class A implements B, C, and D can be used. After an interface is defined, the subclass needs to overwrite the methods in the interface, because the interface methods are not implemented in detail.

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.