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