Source: https://blog.csdn.net/a19881029/article/details/8957441
There are 6 types of relationships between classes:
1. Association is a " has a " relationship
2. Inheritance is a parent -child relationship
3. Realization/Implementation
4. Dependency is a " use a " relationship
5. Aggregation
6. Composition
1. Association
One-way or two-way (usually we need to avoid using two-way association relationship), is a " has a " relationship, if A is unidirectionally related to B, it can be said that A has a B, usually expressed as a global variable
- publicclass Person {
- public Phone phone;
- publicvoid setPhone(Phone phone){
- this.phone = phone;
- }
- public Phone getPhone(){
- return phone;
- }
- }
2.3. Inheritance
A class implements an interface, a class inherits an abstract class, and a class inherits from a parent class belongs to this relationship
4. Dependency
One-way , which means that a class depends on the definition of another class, and changes in one class will affect the other class, which is a " use a " relationship
If A depends on B, then B behaves as A's local variables, method parameters, static method calls, etc.
- publicclass Person {
- publicvoid doSomething(){
- Card card = new Card(); //local variable
- ....
- }
- }
- publicclass Person {
- public void doSomething(Card card){ //Method parameters
- ....
- }
- }
- publicclass Person {
- publicvoid doSomething(){
- int id = Card.getId(); // static method call
- ...
- }
- }
5. Aggregation
One-way, a type of association relationship, the difference between the association relationship is semantic, the two objects associated are usually equal, and the aggregation is generally unequal, there is a sense of the whole and the part, and there is little difference in implementation
Class由Student组成,其生命周期不同,整体不存在了,部分依然存在,当前Team解散了,人还在,还可以加入别的组
- public class Team {
- public Person person;
- public Team(Person person){
- this.person = person;
- }
- }
6. 组合关系(Composition)
单向,是一种强依赖的特殊聚合关系
Head,Body,Arm和Leg组合成People,其生命周期相同,如果整体不存在了,部分也将消亡
- public class Person {
- public Head head;
- public Body body;
- public Arm arm;
- public Leg leg;
- public Person(){
- head = new Head();
- body = new Body();
- arm = new Arm();
- leg = new Leg();
- }
- }