简体   繁体   English

Java OOP - 简单示例中的建模问题(多态)。 组合还是继承?

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

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).我正在尝试用 Java (OOP) 对一些系统进行建模,但我将使用一个更简单的示例来解释我遇到的问题(我认为这与多态和/或继承有关)。 Though I have a feeling that the solution may be to do with Composition.虽然我有一种感觉,解决方案可能与组合有关。

Say simply we have Animal , Species , Bird and Pigeon .简单地说,我们有AnimalSpeciesBirdPigeon The current relationship I have is:我目前的关系是:

  • Pigeon implements/extends Animal , Bird (Pigeon is an animal and a bird) Pigeon实现/扩展Animal , Bird (Pigeon 是一种动物和一种鸟)
  • 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 .但请记住,此设计应可扩展以包含更多AnimalsSpecies

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 .对于List<Animal> ,我希望只能添加Pigeon (和其他动物)而不是SpeciesBird This is satisfied.这就满足了。
  2. For a List<Bird> , I want to be able to add Pigeon (and other birds) only.对于List<Bird> ,我希望只能添加Pigeon (和其他鸟类)。 This is satisfied.这就满足了。
  3. However, for a List<Species> , I want to be able to add Bird (and other species) only;但是,对于List<Species> ,我希望只能添加Bird (和其他物种); 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).然而,通过这种设计的多态性,我也可以添加Pigeon ,这是不受欢迎的(我希望在这个例子中Pigeon不是一个Species )。

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!我希望我已经足够详细地解释了这个例子,但是如果有人对如何建模(使用抽象类、接口、组合、设计模式等)有任何建议,那将不胜感激!

I'll change it like this choosing one between the red or blue relation :我会像这样在红色或蓝色关系之间选择一个来改变它:

在此处输入图片说明

The second point is not satisfied but you could avoid it using composition.第二点不满足,但您可以使用组合来避免它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM