面向对象程序设计中类与类的关系

面向对象程序设计中类与类的关系都有哪几种?分别用类图实例说明。

1. 继承 (Inheritance)

假设有一个Animal类,定义了一些基本的行为如eat()。

Dog类继承自Animal类,并可能添加特定于狗的行为如bark()。

+----------------+

|  Animal        |

| - eat()        |

+----------------+

+------------+------------+

|            |            |

|  Dog       | Cat        |

|            |            |

| - bark()   | - meow()   |

+------------+------------+

2. 组合 (Composition)

假设有一个Car类,它包含一个Engine对象作为其部分之一。

+----------------+

| Engine         |

| - start()      |

+----------------+

+------------+

|  Car       |

|            |

| - engine   |

| - drive()  |

+------------+

3. 聚合 (Aggregation)

假设有一个Department类,它包含多个Employee对象。

+---------------------+

|   Employee          |

| - name              |

+---------------------+

+------------------+

|  Department      |

|                  |

| - employees      |

| - addEmployee()  |

+------------------+

4. 依赖 (Dependency)

假设有一个Calculator类,它使用一个MathOperations类来进行数学运算。

+-------------------+

|  MathOperations   |                   

| - add()           |

| - subtract()      |

+-------------------+

+--------------+

|  Calculator  |

|              |

| - mathOps    |

| - calculate()|

+--------------+

posted @ 2024-12-29 20:19  平安喜乐×  阅读(31)  评论(0)    收藏  举报