Composition, I don't quite get this?

后端 未结 5 989
面向向阳花
面向向阳花 2021-01-21 04:27

Referring to the below link:

http://www.javaworld.com/javaworld/jw-11-1998/jw-11-techniques.html?page=2

The composition approach to code reuse pro

5条回答
  •  礼貌的吻别
    2021-01-21 04:40

    If you would change Fruit.peel()'s return type, you would have to modify Apple.peel() as well. But you don't have to change Apple's interface.

    Remember: The interface are only the method names and their signatures, NOT the implementation.

    Say you'd change Fruit.peel() to return a boolean instead of a int. Then, you could still let Apple.peel() return an int. So: The interface of Apple stays the same but Fruit's changed.

    If you would have use inheritance, that would not be possible: Since Fruit.peel() now returns a boolean, Apple.peel() has to return an boolean, too. So: All code that uses Apple.peel() has to be changed, too. In the composition example, ONLY Apple.peel()'s code has to be changed.

提交回复
热议问题