Java面向对象编程 – 在简单示例中建模的问题(多态)。组合还是继承?

huangapple go评论127阅读模式
英文:

Java OOP - Issue with Modelling in simple example (Polymorphism). Composition or Inheritance?

问题

以下是翻译好的内容:

我正在尝试在Java(面向对象编程)中建模某个系统,但我会使用一个更简单的示例来解释我遇到的问题(我认为与多态性和/或继承有关)。尽管我觉得解决方案可能与组合有关。

假设简单地说,我们有动物物种鸟类鸽子。我目前的关系是:

  • 鸽子实现/继承动物鸟类(鸽子是动物和鸟类)
  • 鸟类实现/继承物种(鸟类是一种物种)

但要记住,这个设计应该可扩展,以包括更多的动物物种

我想要做到以下几点:

  1. 对于一个List<动物>,我希望只能添加鸽子(和其他动物),而不能添加物种鸟类。这个要求已经满足。
  2. 对于一个List<鸟类>,我希望只能添加鸽子(和其他鸟类)。这个要求已经满足。
  3. 然而,对于一个List<物种>,我希望只能添加鸟类(和其他物种);然而,由于这个设计的多态性,我也能添加鸽子,这是不希望的(在这个示例中,我不希望鸽子是一种物种)。

我从未完全理解这一点,但我相信这会遇到我听说过很多问题的继承问题。我希望我已经足够详细地解释了这个示例,但如果有人对如何完全模拟这个示例(使用抽象类、接口、组合、设计模式或其他任何方法)有任何建议,那将非常感谢!

英文:

I am trying to model some system in Java (OOP), but I'll use a simpler example to explain the problem I'm running into (which I believe is to do with Polymorphism and/or Inheritence). Though I have a feeling that the solution may be to do with Composition.

Say simply we have Animal, Species, Bird and Pigeon. The current relationship I have is:

  • Pigeon implements/extends Animal, Bird (Pigeon is an animal and a bird)
  • Bird implements/extends Species (A bird is a species)

Though keep in mind that this design should be extendable to include more Animals and Species.

I want to do the following:

  1. For a List<Animal>, I want to be able to add Pigeon (and other animals) only but not Species or Bird. This is satisfied.
  2. For a List<Bird>, I want to be able to add Pigeon (and other birds) only. This is satisfied.
  3. However, for a List<Species>, I want to be able to add Bird (and other species) only; however, by polymorphism of this design, I'm able to add Pigeon too which is undesirable (I want it such that Pigeon is not a Species in this example).

I never understood this entirely, but I believe this runs into the issues with inheritence that I've heard so much about. I hope I've explained the example in sufficient detail, but if anyone has any suggestions as to how to model this at all (with abstract classes, interfaces, composition, design patterns, anything), that would be very much appreciated!

答案1

得分: 1

我会像这样更改它,在红色或蓝色关系之间进行选择:

Java面向对象编程 – 在简单示例中建模的问题(多态)。组合还是继承?

第二点未满足,但您可以使用组合来避免它。

英文:

I'll change it like this choosing one between the red or blue relation :

Java面向对象编程 – 在简单示例中建模的问题(多态)。组合还是继承?

The second point is not satisfied but you could avoid it using composition.

huangapple
  • 本文由 发表于 2020年8月25日 19:16:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/63577656.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定