6 types of interactive relationships between classes

I. Overview

What are the interactive relationships between classes? There are six relationships between classes defined in UML Unified Modeling Language. They are: generalization, implementation, association, aggregation, combination, and dependence.

2. Detailed explanation

1. Generalization

It can be simply understood as an inheritance relationship. Specifically, the Java code is as follows:

public class A {
    
     ... }
public class B extends A {
    
     ... }
2. Realization

Generally refers to the relationship between interfaces and implementation classes. Specifically, the Java code is as follows:


public interface A {
    
    ...}
public class B implements A {
    
     ... }
3. Aggregation

It is an inclusion relationship. Class A objects include class B objects. The life cycle of class B objects does not depend on the life cycle of class A objects. That is to say, class A objects can be destroyed independently without affecting B objects. For example, the relationship between courses and students relationship between. Specifically, the Java code is as follows:


public class A {
    
    
  private B b;
  public A(B b) {
    
    
    this.b = b;
  }
}
4. Composition

It is also an inclusive relationship. Class A objects contain class B objects. The life cycle of class B objects depends on the life cycle of class A objects. Class B objects cannot exist alone, such as the relationship between a bird and its wings. Specifically, the Java code is as follows:


public class A {
    
    
  private B b;
  public A() {
    
    
    this.b = new B();
  }
}
5. Association

It is a very weak relationship, including aggregation and combination relationships. Specifically at the code level, if the object of class B is a member variable of class A, then class B and class A are related. Specifically, the Java code is as follows:


public class A {
    
    
  private B b;
  public A(B b) {
    
    
    this.b = b;
  }
}
或者
public class A {
    
    
  private B b;
  public A() {
    
    
    this.b = new B();
  }
}
6. Dependency

It is a weaker relationship than an association relationship and includes an association relationship. Whether a class B object is a member variable of a class A object, or a method of class A uses a class B object as a parameter, return value, or local variable, as long as there is any usage relationship between the class B object and the class A object, we call them dependent. relation. Specifically, the Java code is as follows:


public class A {
    
    
  private B b;
  public A(B b) {
    
    
    this.b = b;
  }
}
或者
public class A {
    
    
  private B b;
  public A() {
    
    
    this.b = new B();
  }
}
或者
public class A {
    
    
  public void func(B b) {
    
     ... }
}

Guess you like

Origin blog.csdn.net/qq_42886163/article/details/122383814