Java theory question. There are two classes: class A implements JDesktopPane and class B implements JInternalFrame. Class B is not internal and not nested with respect to class A. How to access an instance of class A from class B? Now I am implementing this by passing an instance of A to constructor B. Is this the best way or is it more convenient?
I ask why, it assumes a situation where an instance of class C will be created from class B, and an instance of class D will be created from it. And so several times. And from an instance of a class, for example, Z, I want to get access to an instance of A. So the link to it should be transferred each time from the constructor to the constructor?
Thank.
- oneThis is a normal way. Passing a link to another object as a constructor parameter, from the design point of view, usually means that the created object (whose constructor) cannot exist without this link. - Igor
- @Igor make a reply? - andreycha
- one@andreycha - easily :) - Igor
- @Artik should add this clarification to the question. - andreycha
2 answers
I’m going to add a little @Igor answer.
Yes, it is normal. In your case, type A is a dependency for type B
As already mentioned, mandatory dependencies are usually passed through the constructor. Optional dependencies are usually set via the properties of the / set methods.
In more complex scenarios, you can get type A instances not directly, but through an object (for example, a factory). In this case, the question arises of contacting the factory itself - the solutions are the same.
At the same time, type B can be a dependency for other types and should be transmitted (implemented) in the same way. In complex applications, such chains can be quite large, so they use containers that facilitate dependency management.
It will be useful to read about:
- inversion of control (inversion of control, IoC)
- dependency injection (DI)
- containers (IoC or DI containers)
There are many sources. You can start from this site , continue with Wikipedia, Google and blogs .
This is a normal way. Passing a link to another object as a constructor parameter, from the design point of view, usually means that the created object (whose constructor) cannot exist without this link.