Perhaps a stupid question, but I just can’t understand if it is possible to link in any way two class files that are in the same package? here are 2 classes circled in red

  • one
    and what is meant by "tie?" - Maxgmer
  • 2
    there is only one public class in one file. If in two files only one class is declared as public, then all can be pushed into one common file. If both classes are public, then only two files are stored - Timur Baimagambetov
  • @Maxgmer, for example, in the 1st file one action is performed, and in the 2nd another, and so that they work together, in one program - Danil S
  • @TimurBaimagambetov and if both classes are public, is it possible, somehow, so to say, to transfer data from the 2nd class to the first? - Danil S
  • of course. You can call Class2 class2 = new Class2 (); in a single class method; and then call its method class2.foo (); - Timur Baimagambetov

1 answer 1

What you want to implement is called dependency.

In the simplest case, you can an instance of one class pass a link to an instance of another and implement a certain dependency:

Class Human { Dog dog; void walkWithDog(int speed) { walk(speed); dog.runAround(this, speed *2); } void walk(int speed) { // do somthing } } 

A person going out for a walk with a dog will not just walk, but will walk the dog, which will run around him with double speed. If an action is performed in the first object, then the action associated with it is performed in the second one, besides the walking speed data is transmitted from the human object to the dog object.

You complicate the Human class, but make the dog run. There are other ways to build dependencies between classes, for example, Aspect-oriented programming.

  • And in my case, when there are 2 source files, does this also work? - Danil S
  • If you can change the code of one of the classes by adding the ability to manage instances of another class, it should work. If not, you can declare another class like "Morning run", which will take the person separately and the dog separately and distribute tasks to them. - Mark
  • Thanks, I will try! - Danil S