Inheritance and composition in Java

Source: Internet
Author: User
Tags getcolor what inheritance

This article mainly explains the concepts of inheritance and composition in java, and the connection and difference between them. first, The article will give a short snippet of code to show what inheritance is. It then shows how to improve the design mechanism of this inheritance through "composition". finally, We summarize the application scenarios of both, that is, whether to choose inheritance or Combination.

1. inheritance

Let's say we have a class called Insect (insect), which contains two methods: 1) moving move (); 2) attacking attack ().

The code is as Follows:

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 (); Suppose the insect had to move first before Attacking.

System.out.println ("Attack");

}

}

now, you want to define a class named Bee (bee). Bee (bee) is a insect (insect), but implements a attack () and move method that differs from the insect (insect). At this point we can implement the Bee class with an inherited design mechanism, just like the following code:

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 ();

}

}

inheritancevscomposition, as a test class, generates an instance of the Bee class in its main method and assigns a reference variable I to the insect type. So when I call the attack method of i, it corresponds to the attack method of the Bee class instance, which is called the attack method of the Bee class.

The inheritance structure of the class is as follows, very simple:

Output:

Output:

Fly

Fly

Attack

The fly was printed two times, which means that the move method was called two Times. however, The Move method should be called only once, because either the insect or the bee is moved only once before an attack.

The problem is in the overloaded code of the attack method of the subclass (that is, the Bee class), which is the sentence Super.attack (). Because in the parent class (that is, The insect class), The Move method is called first when the attack method is called, so when the subclass (Bee) calls Super.attack (), it is equivalent to calling the overloaded Move method at the same time (note that the subclass is overloaded with the move method, Instead of the parent Class's move method).

In order to solve this problem, we can take the following measures:

Delete the attack method of the Subclass. Doing so will make the implementation of the attack method of the subclass entirely dependent on the parent Class's implementation of the method (because the subclass inherits the attack method of the parent class). If the attack method of the parent class is not controlled, the change Occurs. For example, the attack method of the parent class calls the other move method, then the attack method of the subclass will also have the corresponding change, this is a very bad encapsulation.

You can also rewrite the attack method of the subclass, like This:

public void attack () {

Move ();

System.out.println ("Attack");

}

This guarantees the correctness of the result because the attack method of the subclass no longer relies on the parent class. however, the code for the subclass attack method is duplicated with the parent class (the repetitive attack method makes a lot of things complicated, not just more than printing an output statement). So the second way is not, it does not conform to the concept of reuse in software Engineering.

In this case, the inheritance mechanism is flawed: subclasses depend on the implementation details of the parent class, and if the parent class has changed, the consequences of the subclass will be disastrous.

2. combination

In the example above, you can replace inheritance with a combination of mechanisms. Let's take a look at how the application mix is Implemented.

Attack This function is no longer a method, but is abstracted as an interface.

Interface Attack {

public void Move ();

public void Attack ();

}

With the implementation of the attack interface, different types of attack can be defined in the implementation class.

Class Attackimpl implements Attack {

Private String move;

Private String attack;

Public Attackimpl (string move, string Attack) {

This.move = move;

This.attack = attack;

}

@Override

public void Move () {

System.out.println (move);

}

@Override

public void attack () {

Move ();

System.out.println (attack);

}

}

Because the attack function has been abstracted as an interface (tengyun technology ty300.com), the insect class no longer needs to have a attack method.

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;

}

}

The Bee class is a insect class that has attack functionality, so it implements the attack interface:

This encapsulation class encapsulates an object of type attack

Class 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:


Test the class code and pass the instance of Attackimpl as a parameter of type attack to the constructor of the Bee Class:

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 with new method to attack

Bee B = new Bee (1, "black", new Attackimpl ("fly", "sting"));

B.attack ();

}

}

Fly

Move

Fly

Sting

3, when should inherit, when should use combination?

The following two principles explain how inheritance and composition should be selected:

    • If there is a is-a relationship (such as Bee "is a" insect), and one class needs to expose all the method interfaces to another class, then the inheritance mechanism should be used.

    • If there is a has-a relationship (such as Bee "has a" attack Functional Basic Tutorial qkxue.net), then the combination should be Applied.

In summary, inheritance and composition have their usefulness. Only by fully understanding the relationship between the objects and functions can the advantages of the two mechanisms be fully exerted.

Reference:

      1. Http://qkxue.net/info/22865/Java

      2. Http://stackoverflow.com/questions/49002/prefer-composition-over-inheritance

      3. http://www.javaworld.com/article/2076814/core-java/inheritance-versus-composition– Which-one-should-you-choose-.html

Inheritance and 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.