U
U
Urukhayy2016-11-14 18:38:54
Java
Urukhayy, 2016-11-14 18:38:54

How is the open / closed principle implemented in the case of "branching" extensions in Java?

There is an entity that needs to be expanded. Based on all the extension methods that are specified in the OCP, the main one is inheritance. If this entity is expanded in only one direction, then everything is fine. But if this entity needs to be expanded in different directions, what should be done? There is no multiple inheritance in Java.
Example: There is a class - Person.
After some time, they will want to expand this class according to OCP - they will inherit it and make the Bartender class.
But what if later on the class Man wants to be expanded in another direction? For example, the Astronaut class, also inherited from the Human class. Wherein, if you want the Person to be both the Astronaut and the Bartender at the same time, this will not work due to the fact that the Bartender and the Astronaut will already require separate instances, which corresponds to two different people.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey, 2016-11-19
@Urukhayy

the main one is inheritance.

Inheritance of types, not classes. That is, through interfaces.
Java has the ability to do type composition by implementing multiple interfaces. And taking into account the fact that in Java8 you now have the ability to do "default" implementations of methods in interfaces - you have the "correct" inheritance.
And then what if we want to make a bartender robot? I mean that "man" will not always be the base type of "bartender".
In general , Dmitry Roo told you right. "Bartender" is a profession. Property of a person. A person can have many professions:
class Human
{
    Profession[] professions;
}

Thus, we can twist and twirl as we want.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question