Object oriented programming - class design confusion

前端 未结 13 1778
你的背包
你的背包 2021-02-05 22:01

I am trying to wrap my head around object oriented programming.

My understanding is that we have objects so we can design our programs to mirror real-life objects.

13条回答
  •  [愿得一人]
    2021-02-05 22:26

    I tend to think about:

    Is a

    Has a

    So, an apple is a fruit, so inheritance makes sense.

    But, fruit has (is) eatable may make sense, but that shows it is a property of fruit, not an action (method).

    For example, you may have unripened apple, that would not be edible (eatable) so you could then set this property.

    Now, whatever is going to eat this you could set whether an apple is part of it's diet.

    Now Has a would be for composition. So, an apple has a seed would mean that seed doesn't extend apple, but an apple would have a collection of seeds.

    So, you do have a design problem, and I hope that these two concepts may help to clarify.

提交回复
热议问题