Learn from the java-6.4 how to choose between aggregation and inheritance

Source: Internet
Author: User

In this chapter, let's talk about the problem of choosing between aggregation and inheritance.

In our usual code, using aggregation or inheritance can be, or both can be mixed with the line, this time need to make a choice, because the code will need to maintain, how to achieve maintenance simple? Code readable?..

Therefore, we must make a choice in various options.

This is what the author thinks:

If the new class is just a part of the old class, then it is the aggregation that can be used to directly new it, satisfying need or combining the relationship;

If the new class must be a special example of an old class, then it is to use inheritance to satisfy the relationship of is-a or is-like-a

Example:

Cars are means of transport.

Code:

/** *  */package com.ray.ch05;/** * @Package: com.ray.ch05 *  * @TODO Test *  * @date * *  @time 11:42  : * *  @author jmscadmin *  * @version 1.0 */public class Test {}class Vehicle {}class Car extends Vehicle {}class BMW extends Car {}

Car meet is-a vehicles this relationship, BMW satisfies is-a car this relationship


The car is made up of wheels, doors and other combinations.

/** *  */package com.ray.ch05;/** * @Package: com.ray.ch05 *  * @TODO Test *  * @date * *  @time 11:42 : * *  @author jmscadmin *  * @version 1.0 */public class Test {}class Door {}class Wheel {}class Car {private Doo R leftdoor;private Door rightdoor;private Wheel leftforwardwheel;private Wheel leftbackwardwheel;private Wheel Rightforwardwheel;private Wheel Rightbackwardwheel;}

Cars and wheels, doors and other satisfied cars are made up of xxx this relationship.


Summary: This section briefly discusses how to choose between aggregation and inheritance.



This chapter is here, thank you.

-----------------------------------

Directory


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Learn from the java-6.4 how to choose between aggregation and inheritance

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.