0

Is there a way to implement multiple classification in Java? For instance, take this UML diagram - enter image description here

How should the GrainCrop class be implemented?

nsane
  • 1,715
  • 4
  • 21
  • 31

3 Answers3

2

Java does not support multiple inheritance on classes, only interfaces can inherit from multiple interfaces. So what I would do is that the Class GrainCrop in question implements the interface from the two other classes. Then GrainCrop aggregates the two other classes and delegates to the "inner" objects. The calls in GrainCrop can then also be decorated if you need to do additional stuff. E.g.

public void methodFromClassCrop() {
    System.out.println("Stuff before call");
    oneOfTheObjects.methodFromClassCrop();
    System.out.println("Stuff after call");
}

Of course you can only introduce an interface for one of the classes and inherit from the other. It depends on the question if your new class extends one of the other classes in a sense of: introduce new behavior, algorithm, data which uses the other data, or if you just "act" (aggregation in this case) on them.

morpheus05
  • 4,772
  • 2
  • 32
  • 47
2

Interfaces. One or both of Crop and FoodItem would be an interface to be implemented by GrainCrop. So either:

  1. GrainCrop is a Crop (and inherits its behaviors) and exhibits the behavior of FoodItem. In this case Crop is a base class (potentially abstract) and FoodItem is an interface.
  2. GrainCrop is a FoodItem (and inherits its behaviors) and exhibits the behavior of Crop. In this case FoodItem is a base class (potentially abstract) and Crop is an interface.
  3. GrainCrop exhibits the behaviors of both FoodItem and Crop. In this case both FoodItem and Crop are interfaces.

In a single-inheritance environment you take specific care to identify what something "is" vs. what behaviors it exhibits. (This is one of the reasons why interfaces are often described by their behaviors, such as Eatable, rather than their structure, such as FoodItem. It makes the modeling more clear.)

As an often handy over-simplification, think of a base class as what something "is" and an interface as what something "does." An object can only be one thing, but it can do many things.

David
  • 208,112
  • 36
  • 198
  • 279
0

Well, given the fact that FeedItem doesn't appear to have any implementation, I would make it an interface, make Crop a class (possibly abstract), and have GrainCrop extend both of them. You can only extend one class, but you can extend as many interfaces as you want.

atomly
  • 1