How to use methods from an object created in another class?

Basically, I have a method in the Gui class that prints and adds text, and I need to use this method in other classes, such as the Player class. How to use this method? If I had to make another Gui object in the player class, would this create another JPanel that would be bad? If I need to transfer this method to another class, my guest will suggest this. Thanks guys!

+4
source share
1 answer

If the Player class must call methods in the GUI class, why not use the Player class for the GUI instance as a constructor argument? Thus, any code that creates a Player will have to tell him what GUI it should use for such method calls.

This is an approach known as dependency injection, and is generally considered superior to single or static methods.

+5
source

All Articles