the difference between to inheritance compostion
时间: 2024-05-31 11:11:47 浏览: 15
Inheritance and composition are two concepts in object-oriented programming that are used to establish relationships between classes.
Inheritance is a mechanism where a class derives properties and behavior from a parent class. The child class inherits all the properties and methods of the parent class, and can extend or modify them as needed. Inheritance creates an "is-a" relationship between the classes, meaning that the child class is a specific type of the parent class.
Composition, on the other hand, is a mechanism where a class references one or more objects of other classes as its members. The class that references the other objects is called the container, while the objects being referenced are called components. Composition creates a "has-a" relationship between the classes, meaning that the container class has one or more components.
The main difference between inheritance and composition is that inheritance establishes a relationship between classes based on their type, while composition establishes a relationship between classes based on their objects. Inheritance is useful when you want to create a hierarchy of classes, where each class adds more functionality to the previous class. Composition is useful when you want to create complex objects by combining simpler objects, or when you want to reuse code across multiple classes without creating a hierarchy.
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)