Is there a way to implement multiple classification in Java? For instance, take this UML diagram -
How should the GrainCrop
class be implemented?
Is there a way to implement multiple classification in Java? For instance, take this UML diagram -
How should the GrainCrop
class be implemented?
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.
Interfaces. One or both of Crop
and FoodItem
would be an interface to be implemented by GrainCrop
. So either:
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.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.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.
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.