Erik Balen
Erik Balen

Reputation: 275

How do I use methods from an object instantiated in a different class?

Basically I have a method in my Gui class that prints and appends text and I need to use that method in other classes like my Player class. How do I use that method? If I were to make another Gui object in the player class it would create another JPanel which would be bad right? If I need to move that method to another class be my guest to suggest that. Thanks guys!

Upvotes: 4

Views: 163

Answers (1)

StriplingWarrior
StriplingWarrior

Reputation: 156554

If the Player class needs to call methods on the GUI class, why not have the Player class take the GUI instance as a constructor argument? So whatever code creates the Player will have to tell it what GUI it should use for such method calls.

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

Upvotes: 5

Related Questions