Inheritance vs. Composition in Java

Source: Internet
Author: User
Tags getcolor

This article illustrates the concepts of inheritance vs. composition in Java. It first shows an example of inheritance, and then shows how to improve the inheritance design by using composition. How to choose between them was summarized at the end.

1. Inheritance

Let's suppose we have an insect class. This class contains the methods:1) move () and 2) 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 are a type of insect, but has different implement ations of attack ( ) and move (). This can is done by using a inheritance design like 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 as simple as:

Output:

Flyflyattack

"Fly" was printed twice, which indicates move () is called twice. But it should is called only ONCE.

The problem is caused by the Super.attack () method. The attack () method of insect invokes move () method. When the subclass calls Super.attack (), it also invokes the overridden move () method.

To fix the problem, we can:

  1. Eliminate the subclass ' s attack () method. This would make the subclass depends on the super class ' s implementation of attack (). If the Attack () method in the Super class is changed later (which was out of your control), e.g., the Super class ' S attack () method use another method to move, the subclass would need to be changed too. This is the bad encapsulation.
  2. Rewrite the attack () method like the following:
    public void Attack () {move (); System.out.println ("Attack");}

    This would guarantee the correct result, because the subclass was not dependent on the superclass any more. However, the code is the duplicate of the superclass. (Image attack() method does complex things other than just printing a string) This does not following software engineering rule of reusing.

This inheritance design was bad, because the subclass depends on the implementation details of its superclass. If The superclass changes, the subclass may break.

2. Composition

Instead of inheritance, composition can be used in this case. Let's first take a look at the composition solution.

The attack function is abstracted as an interface.

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

Different kinds of attack can be defined by implementing theattackinterface.

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

Since The attack function is extracted,insectdoes does anything related with attack any longer.

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 type of insect, it can attack.

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:

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 do I use Which?

The following-the selection between inheritance and composition:

    1. If There is an is-a relation, and A class wants to expose all the interface to another class, inheritance are likely to Be preferred.
    2. If There is a has-a relationship, composition is preferred.

In summary, inheritance and composition both has their uses, and it pays to understand their relative Merits.

References:
1. Bloch, Joshua. Effective java. Pearson education India, 2008.
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 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.