英文:
Java OOP - Issue with Modelling in simple example (Polymorphism). Composition or Inheritance?
问题
以下是翻译好的内容:
我正在尝试在Java(面向对象编程)中建模某个系统,但我会使用一个更简单的示例来解释我遇到的问题(我认为与多态性和/或继承有关)。尽管我觉得解决方案可能与组合有关。
假设简单地说,我们有动物,物种,鸟类和鸽子。我目前的关系是:
- 鸽子实现/继承动物,鸟类(鸽子是动物和鸟类)
- 鸟类实现/继承物种(鸟类是一种物种)
但要记住,这个设计应该可扩展,以包括更多的动物和物种。
我想要做到以下几点:
- 对于一个
List<动物>
,我希望只能添加鸽子
(和其他动物),而不能添加物种
或鸟类
。这个要求已经满足。 - 对于一个
List<鸟类>
,我希望只能添加鸽子
(和其他鸟类)。这个要求已经满足。 - 然而,对于一个
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:
- For a
List<Animal>
, I want to be able to addPigeon
(and other animals) only but notSpecies
orBird
. This is satisfied. - For a
List<Bird>
, I want to be able to addPigeon
(and other birds) only. This is satisfied. - However, for a
List<Species>
, I want to be able to addBird
(and other species) only; however, by polymorphism of this design, I'm able to addPigeon
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
我会像这样更改它,在红色或蓝色关系之间进行选择:
第二点未满足,但您可以使用组合来避免它。
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论