[英]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 .简单地说,我们有Animal 、 Species 、 Bird和Pigeon 。 The current relationship I have is:
我目前的关系是:
Though keep in mind that this design should be extendable to include more Animals and Species .但请记住,此设计应可扩展以包含更多Animals和Species 。
I want to do the following:我想做以下事情:
List<Animal>
, I want to be able to add Pigeon
(and other animals) only but not Species
or Bird
.List<Animal>
,我希望只能添加Pigeon
(和其他动物)而不是Species
或Bird
。 This is satisfied.List<Bird>
, I want to be able to add Pigeon
(and other birds) only.List<Bird>
,我希望只能添加Pigeon
(和其他鸟类)。 This is satisfied.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!
我希望我已经足够详细地解释了这个例子,但是如果有人对如何建模(使用抽象类、接口、组合、设计模式等)有任何建议,那将不胜感激!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.