简体   繁体   中英

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). 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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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