Question:
Good day!
There is, for example, the Cat class that implements the Movable interface, encapsulates color, and more. Does it make sense to create subclasses of BlackCat, WhiteCat, etc., which, in fact, do not add anything new? Is it correct in this case to create an enum Сats and transfer a specific instance of enum (with its own fields) to the constructor of the Cat class, and then assign field values?
Answer:
It is rather difficult to talk about Schrödinger's spherical cats in a vacuum, since it is not a fact that it will be possible to transfer the experience gained in this matter to a real application.
There are a number of simple ones that can tell you whether to use inheritance or not, or whether some aspect should be just a property.
Relationship "Is" versus relationship "is a property" .
So, can a black cat be said to be a cat in the same sense as a "cat is a mammal"? Those. is the color of some characteristic of the behavior of the modeled entity, which is constant over time? Can we say that "black cats" form a certain group of animals (cats), belonging to which significantly changes their own behavior?
Or can we say that color is one of the attributes of a particular instance, which, moreover, can change over time?
Since the second statement seems more logical, the Color
property should be preferred over subclasses of BlackCat
, RedCat
, etc.
This approach has a number of very important implications.
When something is modeled using a class, then the created object is tightly bound to it. The кот
cannot be changed color for the created object, which may well be real when modeling some behavior (for example, the cat has grown old, it has been shaved).
Plus, hierarchies don't expand well. This means that adding a new color will have to change the hierarchy, which is much more difficult than adding a new enumeration or simply using a different value from the standard Color
enumeration.
Inheritance is designed to model a subset of a common family of objects. Also, inheritance is a very tight relationship that cannot be changed after the object is created, and it is also difficult to extend. Most modern languages do not have multiple inheritance of implementation, which will not allow, in the case of inheritance of colorful cats, to add another "projection" of inheritance, for example, according to the breed of cats or other characteristics.